Beautiful Soup的用法

BEAUTIFUL SOUP的介绍

就是一个非常好用、漂亮、牛逼的第三方库,是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree)。 它提供简单又常用的导航(navigating),搜索以及修改剖析树的操作。它可以大大节省你的编程时间
 
    
# 导入库
 
# 或者
soup = BeautifulSoup(open("index.html"))
# 打印对象的内容,进行格式化的输出
print(soup.prettify())

BEAUTIFUL SOUP的安装

Beautiful Soup 3 目前已经停止开发,推荐在现在的项目中使用Beautiful Soup 4,不过它已经被移植到BS4了,也就是说导入时我们需要 import bs4 。所以这里我们用的版本是 Beautiful Soup 4.3.2 (简称BS4)
easy_install beautifulsoup4
pip install beautifulsoup4

BEAUTIFUL SOUP的使用

2. 初识BeautifulSoup以及使用

 

 
    
# 导入库
from bs4 import BeautifulSoup
# 或者
soup = BeautifulSoup(open("index.html"))
# 打印对象的内容,进行格式化的输出
print(soup.prettify())

其实上述的代码就是将一段html的代码被BeautifulSoup解析,有了这个soup对象之后,其实我们就可以使用BeautifulSoup提供给我们大量的方法进行解析数据了

3. BeautifulSoup的解析器

3.1 Python标准库   (一般使用这个)
使用方法: BeautifulSoup(html_doc,"html.parser")

优势:Python内置,执行速度适中,文档容错能力强

劣势:Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差

3.2 lxml解析器(推荐使用)
使用方法:BeautifulSoup(html_doc,'lxml')

优势:速度快,文档容错能力强(C编写),推荐使用

3.3 html5lib
使用方法:BeautifulSoup(html_doc,"html5lib")

优势:最好的容错性,已浏览器的方式解析文档,生成Html5格式的文档

劣势:速度慢,不依赖外部扩展

 

BEAUTIFULSOUP的四大对象及属性方法

 
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:

Tag
NavigableString
BeautifulSoup
Commen
1. Tag对象
 Tag 是什么?通俗点讲就是 HTML 中的一个个标签,例如
<title>The Dormouse's story</title>
 <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
 
 

那我们怎样通过soup对象方便的获取HTML的内容呢?

其实非常的简单,我们可以使用soup.标签名的方式来轻松的获取内容,不过如果有多个相同的标签,只会找出第一个,如要查询所有的符合条件的标签,后续会介绍到

 
# 获取标题
print(soup.title)
# 获取head信息
print(soup.head)
# 获取a信息
print(soup.a)

Tag对象包含两个重要的属性:name和attrs

name

print(soup.name)
print(soup.head.name)

soup 对象本身比较特殊,它的 name 即为 [document],对于其他内部标签,输出的值便为标签本身的名称。

attrs   键值对格式

获取所有的属性

print(soup.p.attrs) #{'class': ['title'], 'name': 'dromouse'}

获取单独的某个属性

print(soup.p['class']) #['title']
print(soup.p.get('class')) #['title']

修改属性

soup.p['class']="newClass"
print(soup.p) #<p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>

删除属性

del soup.p['class']
print(soup.p)
2.NavigableString

我们使用Tag对象获取了整个标签,那我们想要获取标签内部的内容怎么办?

使用 .string 属性 或者 get_text() 函数即可

 

print(soup.p.string) #The Dormouse's story
print(type(soup.p.string)) #<class 'bs4.element.NavigableString'>
print(soup.p.get_text())

3. BeautifulSoup

BeautifulSoup 对象表示的是一个文档的全部内容.大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性来感受一下

print(type(soup.name))
#<type 'unicode'>
print(soup.name)
# [document]
print(soup.attrs)
#{} 空字典
遍历查询文档树
1. 直接子节点
  • .contents属性

tag 的 .content 属性可以将tag的子节点以列表的方式输出

    
print(soup.head.contents)
#[<title>The Dormouse's story</title>]

输出方式为列表,我们可以用列表索引来获取它的某一个元素

print(soup.head.contents[0])
#<title>The Dormouse's story</title>
  • .children

调用返回的是一个列表生成器对象,我们可以通过遍历来获取所有的节点

print(soup.head.children)
#<listiterator object at 0x7f71457f5710>

循环遍历获取

for child in  soup.body.children:
    print(child)
2. 所有的子孙节点

 .descendants

.contents 和 .children 属性仅包含tag的直接子节点,.descendants 属性可以对所有tag的子孙节点进行递归循环,和 children类似,我们也需要遍历获取其中的内容

for child in soup.descendants:
    print(child)
3. 节点内容
  • .string

如果一个标签里面没有标签了,那么 .string 就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么 .string 也会返回最里面的内容。例如

print(soup.head.string)
#The Dormouse's story
print(soup.title.string)
#The Dormouse's story

如果tag包含了多个子节点,tag就无法确定,string 方法应该调用哪个子节点的内容, .string 的输出结果是 None

print(soup.html.string )
# None
4. 获取多个内容

常用查找方法

1. find_all( name , attrs , recursive , text , **kwargs )

find_all() 方法搜索当前tag的所有子节点,并判断是否符合过滤器的条件

下面是各项参数的解释

name参数

name 参数可以查找所有名字为 name 的tag

传字符串标签

soup.find_all('b')# [<b>The Dormouse's story</b>]
print soup.find_all('a') 
#
[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

传列表

    
soup.find_all(["a", "b"]) 

# [<b>The Dormouse's story</b>,<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

传true

#True 可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点
for tag in soup.find_all(True):
    print(tag.name) # html  head title body p b p a a

关键字参数

传入一个指定的关键字参数如下

soup.find_all(id='link2') # [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

注意:如果想以class关键字查找,但class是python的关键字,怎么办?只需要class_即可,加一个下划线即可

soup.find_all("a", class_="sister") 

# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

可以传入多个指定名字的参数

soup.find_all(class_="sister", id='link1') # [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]

但有些属性也是不能够使用,比如HTML5中的 data-* 属性

data_soup = BeautifulSoup('<div data-foo="value">foo!</div>')
data_soup.find_all(data-foo="value")
# SyntaxError: keyword can't be an expression

解决方法: 通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包含特殊属性的tag

data_soup.find_all(attrs={"data-foo": "value"}) # [<div data-foo="value">foo!</div>]

limit参数

find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果.

soup.find_all("a", limit=2)
# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

recursive参数

调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False

soup.html.find_all("title") # [<title>The Dormouse's story</title>]
 
soup.html.find_all("title", recursive=False) # []

2. find( name , attrs , recursive , text , **kwargs )

它与 find_all() 方法唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果

官方文档:http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/#id78

 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/polly-ling/p/9908970.html