文中示例均使用下面的文档:
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc, 'html.parser')
如果你是Linux用户,那么可以通过系统的软件包管理来安装:
$ apt-get install Python-bs4通过 easy_install 或 pip 来安装,包的名字是 beautifulsoup4 ,这个包兼容Python2和Python3.
$ easy_install beautifulsoup4 $ pip install beautifulsoup4如果你没有安装 easy_install 或 pip ,那你也可以 下载BS4的源码 ,然后通过setup.py来安装.
$ Python setup.py install
soup = BeautifulSoup( doc, paerser, from_encoding )
doc: 一段字符串或一个文件句柄. parser: 文档解析器 from_encoding : 文档的编码
创建一个BeautifulSoup实例:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("index.html"))
soup = BeautifulSoup("<html>data</html>")
BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器
第三方的解析器需要下载:pip install lxml
pip install html5lib
| 解析库 | 使用方法 | 优势 | 劣势 |
| Python标准库 | BeautifulSoup(doc,’html.parser’) | Python内置标准库;执行速度快 | 容错能力较差 |
| lxml HTML解析库 | BeautifulSoup(doc,’lxml’) | 速度快;容错能力强 | 需要安装,需要C语言库 |
| lxml XML解析库 | BeautifulSoup(doc,[‘lxml’,’xml’]) | 速度快;容错能力强;支持XML格式 | 需要C语言库 |
| htm5lib解析库 | BeautifulSoup(doc,’htm5llib’) | 以浏览器方式解析,最好的容错性 | 速度慢 |
如果预先知道文档编码,可以设置编码参数来减少自动检查编码出错的概率并且提高文档解析速度.
在创建 BeautifulSoup 对象的时候设置 from_encoding 参数.
对象的种类
BeautifulSoup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment .
Tag:Tag 对象与XML或HTML原生文档中的tag相同,其最重要的属性:name 和 attributes
BeautifulSoup :该对象表示的是一个文档的全部内容.
Comment 对象是一个特殊类型的 NavigableString 对象:
markup = "<b><!--Hey, buddy. Want to buy a used parser?--></b>" soup = BeautifulSoup(markup) comment = soup.b.string type(comment) # <class 'bs4.element.Comment'> comment # u'Hey, buddy. Want to buy a used parser'
通过标签遍历文档树:
soup.head # <head><title>The Dormouse's story</title></head> soup.title # <title>The Dormouse's story</title> soup.body.b # <b>The Dormouse's story</b> soup.a #只能获取到第一个 # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
.contents 和 .children
tag的 .contents 属性可以将tag的子节点以列表的方式输出。
In [4]: head_tag = soup.head In [5]: head_tag Out[5]: <head><title>The Dormouse's story</title></head> In [6]: head_tag .contents Out[6]: [<title>The Dormouse's story</title>] In [7]: title_tag = head_tag.contents[0] In [8]: title_tag Out[8]: <title>The Dormouse's story</title> In [9]: title_tag.contents Out[9]: ["The Dormouse's story"]
通过 .children 获取到的内容和 .contents 获取的内容一样,但不同的是 .children 是一个迭代对象,而不是列表,只能通过循环的方式获取内容
In [10]: for child in head_tag.children:
...: print(child)
<title>The Dormouse's story</title>
In [11]: head_tag.children
Out[11]: <list_iterator at 0x19f1b961940>
.contents 以及 .children都是获取子节点,获取子孙节点可以通过 .descendants
In [12]: head_tag.descendants
Out[12]: <generator object descendants at 0x0000019F1B384830>
In [13]: for child in head_tag.descendants:
...: print(child)
<title>The Dormouse's story</title>
The Dormouse's story
通过 .parent 属性来获取某个元素的父节点
通过元素的 .parents 属性可以递归得到元素的所有父辈节点
获取兄弟节点
soup.a.next_siblings 获取后面的兄弟节点 soup.a.previous_siblings 获取前面的兄弟节点 soup.a.next_sibling 获取下一个兄弟标签 soup.a.previous_sinbling 获取上一个兄弟标签
搜索文档树:
find_alll :
find_all(name,attrs,recursive,text,**kwargs) 可以传入的参数为:字符串,正则表达式,列表,True,方法
字符串:soup.find_all('b')
正则表达式:soup.find_all(re.compile("^b"))
列表:soup.find_all(["a", "b"])
True:
for tag in soup.find_all(True):
print(tag.name)
方法:
def has_class_but_no_id(tag):
return tag.has_attr('class') and not tag.has_attr('id')
soup.find_all(has_class_but_no_id)
# 第一种方法
print('获取所有的链接')
links = soup.find_all('a')
for link in links:
print(link.name, link['href'], link.get_text())
# 第二种方法
print('获取lacie的链接')
link_node = soup.find('a', href='http://example.com/lacie')
print(link_node.name, link_node['href'], link_node.get_text())
# 第三种方法
print('正则匹配')
link_node = soup.find('a', href=re.compile(r'ill'))
print(link_node.name, link_node['href'], link_node.get_text())
# 第四种方法
print('获取p段落文字')
p_node = soup.find('p', class_='title') # class 在python中属于关键字,这里就用了class_
print(p_node.name, p_node.get_text())
attrs可以传入字典的方式来查找标签:
print(soup.find_all(attrs={'id': 'list-1'}))
print(soup.find_all(attrs={'name': 'elements'})
find
find(name,attrs,recursive,text,**kwargs) find返回的匹配结果的第一个元素其他一些类似的用法:
find_parents()返回所有祖先节点,find_parent()返回直接父节点。 find_next_siblings()返回后面所有兄弟节点,find_next_sibling()返回后面第一个兄弟节点。 find_previous_siblings()返回前面所有兄弟节点,find_previous_sibling()返回前面第一个兄弟节点。 find_all_next()返回节点后所有符合条件的节点, find_next()返回第一个符合条件的节点 find_all_previous()返回节点后所有符合条件的节点, find_previous()返回第一个符合条件的节点
CSS选择器
在 Tag 或 BeautifulSoup 对象的 .select() 方法中传入字符串参数, 即可使用CSS选择器的语法找到tag:
soup.select("title")
通过tag标签逐层查找:
soup.select("body a")
找到某个tag标签下的直接子标签 :
soup.select("head > title")
找到兄弟节点标签:
soup.select("#link1 ~ .sister")
通过CSS的类名查找:
soup.select(".sister")
通过tag的id查找:
soup.select("#link1")
同时用多种CSS选择器查询元素:
soup.select("#link1,#link2")
通过是否存在某个属性来查找:
soup.select('a[href]')
通过属性的值来查找:
soup.select('a[href="http://example.com/elsie"]')
返回查找到的元素的第一个
soup.select_one(".sister")
2174




被折叠的 条评论
为什么被折叠?



