BeautifulSoup是一个可以从HTML或XML文件中提取数据的Python库,简单来说,它能将HTML的标签文件解析成树形结构,然后方便地获取到指定标签的对应属性。这个特性lxml 差不多。
BeautifulSoup的安装
BeautifulSoup3目前已经停止开发,推荐在现在的项目中使用BeautifulSoup4,安装方法:
pip install beautifulsoup4
BeautifulSoup的解析器
如果仅是想要解析HTML文档,只要用文档创建BeautifulSoup对象就可以了。BeautifulSoup会自动选择一个解析器来解析文档。但是还可以通过参数指定使用那种解析器来解析当前文档。BeautifulSoup第一个参数应该是要被解析的文档字符串或是文件句柄,第二个参数用来标识怎样解析文档。如果第二个参数为空,那么BeautifulSoup根据当前系统安装的库自动选择解析器,解析器的优先数序:lxml, html5lib, Python标准库。
下面两种条件下解析器优先顺序会变化:
- 要解析的文档是什么类型:目前支持“html”,“xml”,和“html5”
- 指定使用哪种解析器:目前支持“lxml”,“html5lib”,和“parser”
如果指定的解析器没有安装BeautifulSoup会自动选择其它方案。目前只有lxml解析器支持XML文档的解析,在没有安装lxml库的情况下创建beautifulsoup对象时无论是否指定使用lxml都无法得到解析后的对象。
安装解析器:
- lxml,Windows安装可能会出现问题,具体安装流程见lxml与xpath
- html5lib直接执行:
pip install html5lib
下表列出了主要的解析器及它们的优缺点:
解析器 | 使用方法 | 优势 | 劣势 |
Python标准库 | BeautifulSoup(markup, “html.parser”) | Python的内置标准库
执行速度适中 文档容错能力强 |
Python2.7.3or3.2.2前的版本中文档容错能力差 |
lxmlHTML解析器 | BeautifulSoup(markup, “lxml”) | 速度快
文档容错能力强 |
需要安装C语言库 |
lxmlXML解析器 | BeautifulSoup(markup, [“lxml”, “xml”])
BeautifulSoup(markup, “xml”) |
速度快
唯一支持XML的解析器 |
需要安装C语言库 |
html5lib | BeautifulSoup(markup, “html5lib”) | 最好的容错性
以浏览器的方式解析文档 生成HTML5格式的文档 |
速度慢
不依赖外部扩展 |
这里推荐使用lxml作为解析器,因为效率更高。
BeautifulSoup的使用
创建BeautifulSoup对象
# -*- coding:utf-8 -*- from bs4 import BeautifulSoup import requests url = 'https://www.biaodianfu.com' r = requests.get(url, timeout=20) soup = BeautifulSoup(r.content, 'html.parser') print(type(soup)) print(soup)
BeautifulSoup构造方法的第二个参数为文档解析器,若不传入该参数,BeautifulSoup会自行选择最合适的解析器来解析文档,不过会有警告提示。也可以通过文件句柄来初始化,可先将HTML的源码保存到本地同级目录reo.html,然后将文件名作为参数:
soup = BeautifulSoup(open('test.html'))
BeautifulSoup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:
Tag
Tag是什么?通俗点讲就是HTML中的一个个标签,下面我们来感受一下怎样用BeautifulSoup来方便地获取Tags:
print(soup.title) print(soup.h1)
我们可以利用soup加标签名轻松地获取这些标签的内容,不过有一点是,它查找的是在所有内容中的第一个符合要求的标签,如果要查询所有的标签,我们在后面进行介绍。
对于Tag,它有两个重要的属性,是name和attrs:
- name:soup对象本身比较特殊,它的name即为[document],对于其他内部标签,输出的值便为标签本身的名称。
- attrs:一个Tag对象可以有多个属性,操作方法和字典相同,属性包含key和value,同样可以获取value的信息。
print(soup.p.attrs) print(soup.p['class']) print(soup.p.get('class')) #等价print(soup.p['class'])
tag的属性可添加、删除(delsoup.b[‘class’])、修改,和字典方法相同。如果一个属性key对应多个value,则返回一个value的list。
NavigableString
既然我们已经得到了标签的内容,那么问题来了,我们要想获取标签内部的文字怎么办呢?很简单,用.string即可,Tag中的字符串即为NavigableString对象。
print(soup.p.string)
在BeautifulSoup之外使用该类型,推荐转换为Unicode:unicode(Tag.string)。tag能够包含其他tag或字符串,而NavigableString则不能包含其他对象。不支持.content,.string,find(),只支持部分遍历文档树和搜索文档树中的属性。
Comment
Comment对象是一个特殊类型的NavigableString对象,其实输出的内容仍然不包括注释符号,但是如果不好好处理它,可能会对我们的文本处理造成意想不到的麻烦。
我们找一个带注释的标签
print(soup.a) print(soup.a.string) print(type(soup.a.string))
运行结果如下:
<a class="sister" href="http://example.com/elsie" id="link1"><!--Elsie--></a> Elsie <class 'bs4.element.Comment'>
a标签里的内容实际上是注释,但是如果我们利用.string来输出它的内容,我们发现它已经把注释符号去掉了,所以这可能会给我们带来不必要的麻烦。
另外我们打印输出下它的类型,发现它是一个Comment类型,所以,我们在使用前最好做一下判断,判断代码如下:
if type(soup.a.string) == bs4.element.Comment: print(soup.a.string)
上面的代码中,我们首先判断了它的类型,是否为Comment类型,然后再进行其他操作,如打印输出。
遍历文档树
BeautifulSoup对象作为一棵树,有多个节点。对于一个节点,相对于它所在的位置,有子节点、父节点、兄弟节点。
子节点
一个Tag可包含多个Tag以及字符串,这些都是这个Tag的子节点。而NavigableString不会有子节点。
直接子节点
.contentstag的.content属性可以将tag的子节点以列表的方式输出:
print(soup.head.contents) #[<title>The Dormouse's story</title>]
.children它返回的不是一个list,不过我们可以通过遍历获取所有子节点。
print(soup.head.children) #<listiterator object at 0x7f71457f5710> for child in soup.body.children: print(child)
如果想要获得某个Tag,上述已提到方法:
soup.tag_name
通过点取属性,只能获得当前名字的第一个tag,若要获取所有,需要使用搜索文档树中的方法:
soup.find_all('tag_name')
tag的.contents属性可将所有子节点以列表的方式输出。可通过tag的.children生成器,对所有子节点进行遍历。.contents和.children只对获取Tag的直接子节点,.descendants可用于对Tag的所有子孙节点进行遍历。
如果tag只有一个NavigableString类型子节点,则可用.string获取。如果包含多个,使用.strings遍历。若输出的字符串中包含空格或空行,使用.stripped_strings去除。
所有子孙节点
.contents和.children属性仅包含tag的直接子节点,.descendants属性可以对所有tag的子孙节点进行递归循环,和children类似,我们也需要遍历获取其中的内容。
for child in soup.descendants: print child
如果tag只有一个NavigableString类型子节点,那么这个tag可以使用.string得到子节点。如果一个tag仅有一个子节点,那么这个tag也可以使用.string方法,输出结果与当前唯一子节点的.string结果相同。
通俗点说就是:如果一个标签里面没有标签了,那么.string就会返回标签里面的内容。如果标签里面只有唯一的一个标签了,那么.string也会返回最里面的内容。例如
print(soup.head.string) #The Dormouse's story print(soup.title.string) #The Dormouse's story
如果tag包含了多个子节点,tag就无法确定,string方法应该调用哪个子节点的内容,.string的输出结果是None
获取多个内容,不过需要遍历获取,比如下面的例子:
for string in soup.strings: print(repr(string)) #u"The Dormouse's story" #u'\n\n' #u"The Dormouse's story" #u'\n\n' #u'Once upon a time there were three little sisters; and their names were\n' #u'Elsie' #u',\n' #u'Lacie' #u'and\n' #u'Tillie' #u';\nand they lived at the bottom of a well.' #u'\n\n' #u'...' #u'\n'
.stripped_strings,输出的字符串中可能包含了很多空格或空行,使用.stripped_strings可以去除多余空白内容:
for string in soup.stripped_strings: print(repr(string)) #u"The Dormouse's story" #u"The Dormouse's story" #u'Once upon a time there were three little sisters; and their names were' #u'Elsie' #u',' #u'Lacie' #u'and' #u'Tillie' #u';\nand they lived at the bottom of a well.' #u'...'
父节点
p = soup.p print(p.parent.name) #body content = soup.head.title.string print(content.parent.name) #title
全部父节点
通过元素的.parents属性可以递归得到元素的所有父辈节点,例如
content = soup.head.title.string for parent in content.parents: print(parent.name)
返回数据:
title head html [document]
兄弟节点
兄弟节点可以理解为和本节点处在统一级的节点,.next_sibling属性获取了该节点的下一个兄弟节点,.previous_sibling则与之相反,如果节点不存在,则返回None。
注意:实际文档中的tag的.next_sibling和.previous_sibling属性通常是字符串或空白,因为空白或者换行也可以被视作一个节点,所以得到的结果可能是空白或者换行。
print(soup.p.next_sibling) print(soup.p.prev_sibling) print(soup.p.next_sibling.next_sibling)
全部兄弟节点通过 .next_siblings 和 .previous_siblings 属性可以对当前节点的兄弟节点迭代输出。
for sibling in soup.a.next_siblings: print(repr(sibling)) # u',\n' # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> # u'and\n' # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a> # u'; and they lived at the bottom of a well.' # None
.next_element .previous_element 属性与 .next_sibling .previous_sibling 不同,它并不是针对于兄弟节点,而是在所有节点,不分层次。
所有前后节点
通过 .next_elements 和 .previous_elements 的迭代器就可以向前或向后访问文档的解析内容,就好像文档正在被解析一样。
for element in last_a_tag.next_elements: print(repr(element)) # u'Tillie' # u';\nand they lived at the bottom of a well.' # u'\n\n' # <p class="story">...</p> # u'...' # u'\n' # None
以上是遍历文档树的基本用法。
搜索文档树
find_all(name, attrs, recursive, text, **kwargs)
find_all() 方法搜索当前 tag 的所有 tag 子节点,并判断是否符合过滤器的条件。
name 参数
可以查找所有名字为 name 的 tag,字符串对象会被自动忽略掉。
A. 传字符串
最简单的过滤器是字符串。在搜索方法中传入一个字符串参数 BeautifulSoup 会查找与字符串完整匹配的内容,下面的例子用于查找文档中所有的 <b> 标签。
print(soup.find_all('a'))
B. 传正则表达式
如果传入正则表达式作为参数 BeautifulSoup 会通过正则表达式的 match() 来匹配内容。下面例子中找出所有以 b 开头的标签,这表示 <body> 和 <b> 标签都应该被找到:
import re for tag in soup.find_all(re.compile("^b")): print(tag.name) # body # b
C. 传列表
如果传入列表参数 BeautifulSoup 会将与列表中任一元素匹配的内容返回。下面代码找到文档中所有 <a> 标签和 <b> 标签。
soup.find_all(["a", "b"])
D. 传 True
True 可以匹配任何值,下面代码查找到所有的 tag 但是不会返回字符串节点
for tag in soup.find_all(True): print(tag.name)
E. 传方法
如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False。
下面方法校验了当前元素,如果包含 class 属性却不包含 id 属性那么将返回 True:
def has_class_but_no_id(tag): return tag.has_attr('class') and not tag.has_attr('id')
将这个方法作为参数传入 find_all() 方法,将得到所有 <p> 标签:
soup.find_all(has_class_but_no_id) # [<p class="title"><b>The Dormouse's story</b></p>, # <p class="story">Once upon a time there were...</p>, # <p class="story">...</p>]
keyword 参数
注意:如果一个指定名字的参数不是搜索内置的参数名,搜索时会把该参数当作指定名字 tag 的属性来搜索,如果包含一个名字为 id 的参数,BeautifulSoup 会搜索每个 tag 的”id”属性。
soup.find_all(id='link2') # [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
如果传入 href 参数,BeautifulSoup 会搜索每个 tag 的”href”属性。
soup.find_all(href=re.compile("elsie")) # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>]
使用多个指定名字的参数可以同时过滤 tag 的多个属性:
soup.find_all(href=re.compile("elsie"), id='link1') # [<a class="sister" href="http://example.com/elsie" id="link1">three</a>]
在这里我们想用 class 过滤,不过 class 是 python 的关键词,这怎么办?加个下划线就可以
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('tag.name', attrs={'class': 'class_value'})
有些 tag 属性在搜索不能使用,比如 HTML5 中的 data-* 属性
data_soup = BeautifulSoup('foo!') 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"}) # [foo!]
text 参数
通过 text 参数可以搜索文档中的字符串内容。与 name 参数的可选值一样,text 参数接受字符串、正则表达式、列表、True
soup.find_all(text="Elsie") # [u'Elsie'] soup.find_all(text=["Tillie", "Elsie", "Lacie"]) # [u'Elsie', u'Lacie', u'Tillie'] soup.find_all(text=re.compile("Dormouse")) [u"The Dormouse's story", u"The Dormouse's story"]
limit 参数
find_all() 方法返回全部的搜索结构,如果文档树很大那么搜索会很慢。如果我们不需要全部结果可以使用 limit 参数限制返回结果的数量。效果与 SQL 中的 limit 关键字类似,当搜索到的结果数量达到 limit 的限制时就停止搜索返回结果。
文档树中有 3 个 tag 符合搜索条件但结果只返回了 2 个,因为我们限制了返回数量:
soup.find_all("a", limit=2)
recursive 参数
调用 tag 的 find_all() 方法时 BeautifulSoup 会检索当前 tag 的所有子孙节点,如果只想搜索 tag 的直接子节点可以使用参数 recursive=False。
soup.html.find_all("title") # [The Dormouse's story ] soup.html.find_all("title", recursive=False) # []
find(name, attrs, recursive, text, **kwargs)
find() 方法等价于 find_all(limit=1),返回符合条件的第一个对象。它与 find_all() 方法唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表而 find() 方法直接返回结果。
除了 find() 和 find_all() 之外还有一些搜索的方法:
- find_parent()
- find_next_sibling()
- find_previous_sibling()
上面三种可以在后面加 ‘s’ 表示所有。
- find_next()
- find_previous()
- find_all_next()
- find_all_previous()
find_parents() find_parent()
find_all() 和 find() 只搜索当前节点的所有子节点, 孙子节点等. find_parents() 和 find_parent() 用来搜索当前节点的父辈节点, 搜索方法与普通 tag 的搜索方法相同, 搜索文档搜索文档包含的内容
find_next_siblings() find_next_sibling()
这 2 个方法通过 .next_siblings 属性对当 tag 的所有后面解析的兄弟 tag 节点进行迭代, find_next_siblings() 方法返回所有符合条件的后面的兄弟节点, find_next_sibling() 只返回符合条件的后面的第一个 tag 节点
find_previous_siblings() find_previous_sibling()
这 2 个方法通过 .previous_siblings 属性对当前 tag 的前面解析的兄弟 tag 节点进行迭代, find_previous_siblings() 方法返回所有符合条件的前面的兄弟节点, find_previous_sibling() 方法返回第一个符合条件的前面的兄弟节点
find_all_next() find_next()
这 2 个方法通过 .next_elements 属性对当前 tag 的之后的 tag 和字符串进行迭代, find_all_next() 方法返回所有符合条件的节点, find_next() 方法返回第一个符合条件的节点
find_all_previous() 和 find_previous()
这 2 个方法通过 .previous_elements 属性对当前节点前面的 tag 和字符串进行迭代, find_all_previous() 方法返回所有符合条件的节点, find_previous() 方法返回第一个符合条件的节点
注:以上方法参数用法与 find_all() 完全相同,原理均类似,在此不再赘述。
CSS 选择器
我们在写 CSS 时,标签名不加任何修饰,类名前加点,id 名前加 #,在这里我们也可以利用类似的方法来筛选元素,用到的方法是 soup.select(),返回类型是 list
通过标签名查找
print(soup.select('title')) # [The Dormouse's story ] print(soup.select('a')) # [, Lacie, Tillie] print(soup.select('b')) # [The Dormouse's story]
通过类名查找
print(soup.select('.sister')) # [, Lacie, Tillie]
通过 id 名查找
print(soup.select('#link1')) # []
组合查找
组合查找即和写 class 文件时,标签名与类名、id 名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1 的内容,二者需要用空格分开
print(soup.select('p #link1')) #[]
直接子标签查找
print(soup.select("head > title")) #[The Dormouse's story ]
属性查找
查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。
print(soup.select('a[class="sister"]')) #[, Lacie, Tillie] print(soup.select('a[href="http://example.com/elsie"]')) #[]
同样,属性仍然可以与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格
print(soup.select('p a[href="http://example.com/elsie"]')) #[]
以上的 select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容。get_text(strip=True) 可去除文本前后的空白。
soup = BeautifulSoup(html, 'lxml') print(type(soup.select('title'))) print(soup.select('title')[0].get_text()) for title in soup.select('title'): print title.get_text()
编码问题
BeautifulSoup 默认自动将输入文档转换为 Unicode 编码,输出文档转换为 utf-8 编码。BeautifulSoup 对象的 .original_encoding 属性来获取自动识别编码的结果。当然这样比较慢,有时候会出错。使用 chartdet 库可提高编码检测效率。可以在创建 BeautifulSoup 对象时,指定入参 from_encoding 来告知文档的编码方式。有时候转码时有些特殊字符替换成了特殊的 Unicode,可通过 BeautifulSoup 对象的 .contains_repalcement_characters 属性来判断是否有此情况,为 True 即为有特殊替换。