是一个可以从HTML或XML文件中提取数据的Python库.
能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.
Beautiful Soup会帮你节省数小时甚至数天的工作时间.
后面的内容,我们会把Beautiful Soup简称为BS
下面的一段HTML代码将作为例子被多次用到.这是 爱丽丝梦游仙境的 的一段内容(以后内容中简称为 爱丽丝 的文档):
定义了一个变量 保存一个html字符串
html_doc = """
爱丽丝历险记爱丽丝历险记
Once upon a time there were three little sisters; and their names were
Lacie and
and they lived at the bottom of a well.
...
"""
BS会把一个字符串解析为BS的对象
使用BeautifulSoup解析这段代码,能够得到一个 BeautifulSoup 的对象,并能按照标准的缩进格式的结构输出:from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())
#
#
#
# 爱丽丝历险记
#
#
#
#
#
# 爱丽丝历险记
#
#
#
# Once upon a time there were three little sisters; and their names were
# Elsie
#
# ,
# Lacie
#
# and
# Tillie
#
# ; and they lived at the bottom of a well.
#
#
# ...
#
#
#
上面代码我们可以看到 bs4帮我们把不完整的html代码格式化成了完整的html代码 这样我们就可以去操作HTML这棵树了