📅  最后修改于: 2023-12-03 15:07:02.825000             🧑  作者: Mango
儿童生成器Python Beautifulsoup是一个Python库,用于从HTML或XML文档中提取数据。它通过解析DOM树来实现这一功能,并提供了一系列工具来搜索、遍历、修改DOM树中的元素。
安装Beautifulsoup可以使用pip指令:
!pip install beautifulsoup4
用法示例:
from bs4 import BeautifulSoup
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>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())
结果应该是格式化的HTML源代码。
<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 class="sister" href="http://example.com/elsie" id="link1">
Elsie
</a>
,
<a class="sister" href="http://example.com/lacie" id="link2">
Lacie
</a>
and
<a class="sister" href="http://example.com/tillie" id="link3">
Tillie
</a>
; and they lived at the bottom of a well.
</p>
<p class="story">
...
</p>
</body>
</html>
可以使用多种方法来搜索DOM树:
soup = BeautifulSoup(html_doc, 'html.parser')
# 搜索第一个符合条件的标签
soup.find('p')
# 搜索所有符合条件的标签
soup.find_all('a')
# 根据标签属性搜索
soup.find_all('a', {'class': 'sister'})
# 搜索特定的标签文本内容
soup.find_all('a', string='Lacie')
使用Beautifulsoup可以非常方便地从HTML或XML文档中提取数据,特别是对于爬取网站数据的程序员来说非常有用。标准的DOM树操作和搜索语法好像也非常容易理解。