1. BeautifulSoup 简介
BeautifulSoup 和lxml一样是一个HTML/XML解析器,主要功能是解析和提取HTML/XML数据
与lxml不同的是,BeautifulSoup是基于HTML DOM(文档对象模型),会载入整个文档解析整个DOM树,因此时间和内存的开销都会大很多,所有性能会低于lxml。
1.1 解析工具对比:
1.2 简单使用
当没有解析器时,解析文档不会报错,但会给出警告:
Warning 内容:
UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.
大概的意思就是说,没有给定解析器,于是这里默认使用了最好的解析器lxml,但是如果你在不同的系统和环境运行时将会使用不同的解析器因此得到的结果也不一定相同。
官方推荐使用的是lxml。
使用解析器之后我们发现即使html文档不完善,lxml解析时也会将不完善的部分进行一个补齐,这就是我们上面看到的图片中的内容。
然后通常情况下,html的格式是有一定的缩进来区分每个模块的,那么这个操作在BeautifulSoup里面也是很容易实现的,只需要在soup调用prettify()这个函数即可,运行结果如下:
2. 四个常用对象
2.1 Tag
Tag 就是html中的标签,使用时直接利用soup. 加上标签名即可查找到标签内容。
需要注意的是:tag查找到的标签是在所有内容里第一个符合要求的标签。
soup = BeautifulSoup(html, 'lxml')
print(soup.p)
print(type(soup.p))#查看类型
#两个重要属性name, attrs
print(soup.head.name)
print(soup.p.name)
print(soup.p.attrs)
print(soup.p['class'])
print(soup.p.get('class'))
soup.p['class'] = 'new'
print(soup.p.attrs)
结果:
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<class 'bs4.element.Tag'>
head
p
{'class': ['title'], 'name': 'dromouse'}
['title']
['title']
{'class': 'new', 'name': 'dromouse'}
2.2 NavigableString
NavigableString这个标签可以获取标签中的内容文字。
还是接着上面的例子,导入NavigableString模块,使用即可。
2.3 BeautifulSoup
BeautifulSoup对象表示的是一个文档的全部内容,大部分时候,可以把它当作Tag对象,BeautifulSoup支持遍历文档树和搜索文档树中大部分方法。
在BeautifulSoup源码中继承自Tag。
2.3.1 遍历文档树
- contents 返回所有子节点的列表
- children 返回所有子节点的迭代器
from bs4.element import Comment
head_tag = BeautifulSoup(html, 'lxml')
print(head_tag.contents) #返回时list
print(head_tag.children)
for i in head_tag.children:
print(i)
- strings:如果tag包含多个字符串,可以使用.string来循环获取,返回生成器
for string in soup.strings:
print(string)
print(repr(string))
The Dormouse's story
"The Dormouse's story"
'\n'
'\n'
The Dormouse's story
"The Dormouse's story"
'\n'
Once upon a time there were three little sisters; and their names were
'Once upon a time there were three little sisters; and their names were\n'
,
',\n'
Lacie
'Lacie'
and
' and\n'
Tillie
'Tillie'
;
and they lived at the bottom of a well.
';\nand they lived at the bottom of a well.'
'\n'
...
'...'
'\n'
'\n'
Process finished with exit code 0
- stripped_string:.stripped_strings 可以去除输出字符串中多余空白内容或空行,返回生成器
for string in soup.stripped_strings:
print(string)
# print(repr(string))
The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
,
Lacie
and
Tillie
;
and they lived at the bottom of a well.
...
Process finished with exit code 0
-
get_text:获取某个标签的子孙非标签字符串,以普通字符串返回
2.3.2 搜索文档树
详见下一篇博客:
https://blog.csdn.net/weixin_44566432/article/details/108664325
2.4 Comment
Comment 对象是一个特殊类型的NavigableString对象