BeautifulSoup 是一个用于解析 HTML 和 XML 文档的 Python 库。它能够从网页中提取数据,而且由于其易用性,BeautifulSoup 常被用于网络爬虫中。以下是 BeautifulSoup 的基本使用方法和一些代码示例。
安装 BeautifulSoup
首先,你需要安装 BeautifulSoup 库,以及一个解析器库,如 lxml 或 html.parser。通常 lxml 更快,但 html.parser 是 Python 内置的,不需要额外安装。
pip install beautifulsoup4
pip install lxml # 或者 pip install html5lib
BeautifulSoup 基本用法
代码示例(解析 HTML):
from bs4 import BeautifulSoup
# 假设我们有一段 HTML 内容
html_doc = "<html><head><title>The Dormouse's story</title></head><body>"
html_doc += "<p class='title'><b>The Dormouse's story</b></p>"
html_doc += "<p class='story'>Once upon a time there were three little sisters</p></body></html>"
# 创建一个 BeautifulSoup 对象,第二个参数是解析器名称
soup = BeautifulSoup(html_doc, 'html.parser')
# 获取标题
print(soup.title.string)
# 通过标签名获取所有段落
paragraphs = soup.find_all('p')
for p in paragraphs:
print(p.text)
# 使用 CSS 选择器
print(soup.select_one('p.title > b').text)
提取数据
代码示例(提取链接):
from bs4 import BeautifulSoup
# 假设我们从网页获取了 HTML 内容
html = '<html><head></head><body><a href="http://example.com">Example</a></body></html>'
soup = BeautifulSoup(html, 'html.parser')
# 提取所有链接的 URL
for link in soup.find_all('a'):
print(link['href'])
处理嵌套数据
代码示例(提取表格数据):
from bs4 import BeautifulSoup
html = """
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<!-- 更多行 -->
</table>
"""
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
for row in rows:
cells = row.find_all('td')
print([cell.text for cell in cells])
与 Requests 库结合使用
代码示例(从网页抓取数据):
import requests
from bs4 import BeautifulSoup
# 发送 HTTP 请求
response = requests.get('http://example.com')
# 解析响应内容
soup = BeautifulSoup(response.text, 'html.parser')
# 提取数据
print(soup.title.text)
异常处理
在使用 BeautifulSoup 时,也可能会遇到一些异常情况,如找不到标签或属性。使用 try-except 语句可以处理这些异常。
代码示例(异常处理):
from bs4 import BeautifulSoup
soup = BeautifulSoup("<tag>no attributes</tag>", 'html.parser')
try:
# 尝试获取不存在的属性
print(soup.tag['nonexistent'])
except KeyError as e:
print(f"Attribute not found: {e}")
`