文章目录
- 1. 文档地址
- 2. 安装
- 3. 使用
- 4. 解析器
- 5. 对象的种类
- 6. 遍历
- 7. 格式化与编码
1. 文档地址
beautifulSoup4 文档
2. 安装
pip3 install beautifulsoup4
3. 使用
from bs4 import BeautifulSoupsoup = BeautifulSoup(open("index.html"))soup = BeautifulSoup("data")
4. 解析器
- 推荐使用
lxml
作为解析器,因为效率更高 Python2.7.3
之前的版本和Python3
中3.2.2之前的版本,必须安装lxml
或html5lib
, 因为那些Python版本的标准库中内置的HTML
解析方法不够稳定
解析器 | 使用方法 | 优势 | 劣势 |
---|
Python 标准库 | BeautifulSoup(markup, "html.parser") | Python的内置标准库执行速度适中文档容错能力强 | Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差 |
lxml HTML 解析器 | BeautifulSoup(markup, "lxml") | 速度快文档容错能力强 | 需要安装C语言库 |
lxml XML 解析器 | BeautifulSoup(markup, ["lxml-xml"])``BeautifulSoup(markup, "xml") | 速度快唯一支持XML的解析器 | 需要安装C语言库 |
html5lib | BeautifulSoup(markup, "html5lib") | 最好的容错性以浏览器的方式解析文档生成HTML5格式的文档 | 速度慢不依赖外部 |
5. 对象的种类
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hrO4xBRO-1678856014746)(beautifulSoup.assets/image-20230315114102272.png)]](https://img.pic99.top/hfjzjc/202505/5eac31cf0e6ea7e.png)
soup = BeautifulSoup('Extremely bold')
tag = soup.b
type(tag)
#
基本元素 | 类型 | 说明 |
---|
Name | tag中最重要的属性: name和attributes | 标签名字,通过 .name 来获取 |
tag.name
# 'b'
基本元素 | 类型 | 说明 |
---|
Attributes | tag中最重要的属性: name和attributes | 标签的属性;tag[‘class’]或者tag.attrs获取 |
tag['class']
# 'boldest'# 或者
tag.attrs
# {'class': 'boldest'}
基本元素 | 类型 | 说明 |
---|
NavigableString | | 标签内非属性字符串,标签内容文本;tag.string 获取 |
tag.string
# 'Extremely bold'
type(tag.string)
#
基本元素 | 类型 | 说明 |
---|
Comment | | 注释部分;tag.string 获取 |
markup = ""
soup = BeautifulSoup(markup)
comment = soup.b.string # 'Hey, buddy. Want to buy a used parser'
type(comment)
#
6. 遍历
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-In8VU7iZ-1678856014747)(beautifulSoup.assets/image-20230315120817033.png)]](https://img.pic99.top/hfjzjc/202505/6c8fd4b0c9f8a69.png)
6.1 下行遍历
属性 | 说明 |
---|
.contents | 儿子节点列表,其中‘\n’换行也作为列表的一个元素【当前节点下一层】 |
.children | 与.contents类似,用于遍历儿子节点【当前节点下一层】 |
.descendants | 子孙节点的迭代类型,包含所有子孙节点,用于遍历循环【当前节点后续所有节点】 |
6.2 上行遍历
属性 | 说明 |
---|
.parent | 父节点 |
.parents | 所有父辈节点 |
link = soup.a
link
# Elsie
for parent in link.parents:if parent is None:print(parent)else:print(parent.name)
# p
# body
# html
# [document]
# None
6.3 平行遍历
属性 | 说明 |
---|
.next_sibling | 当前节点的下一个兄弟节点 |
.previous_sibling | 当前节点的上一个兄弟节点 |
.next_siblings | 当前节点的下面的所有兄弟节点 |
.previous_siblings | 当前节点的上面的所有兄弟节点 |
7. 格式化与编码
7.1 格式化
格式化 | 说明 |
---|
prettify()方法 | 加入 \n 格式化 HTML |
 | |
7.2 编码
bs4库
将读入的内容都转换成了UTF-8
编码;Python3
默认支持UTF-8
编码;建议使用bs4库时用Python3