BeautifulSoup
是一个用于解析 HTML 和 XML 文档的 Python 库。
它提供了简洁的接口和强大的功能,使得从网页中提取信息变得非常容易。BeautifulSoup
通常与 requests
库结合使用,用于抓取网页内容并解析它们。
首先,你需要安装 beautifulsoup4
包以及常用的解析器库(如 lxml
或 html5lib
)。可以通过 pip 来安装:
bashpip install beautifulsoup4
下载 lxml
解析器:
bashpip install lxml
或者如果你更喜欢 html5lib
解析器:
bashpip install html5lib
以下是一些具体的示例,展示了如何使用 BeautifulSoup
进行网页解析和数据提取。
假设我们有一个简单的 HTML 文档,并希望通过 BeautifulSoup
解析它:
pythonfrom 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>
"""
# 创建 BeautifulSoup 对象
soup = BeautifulSoup(html_doc, 'html.parser')
# 输出美化后的 HTML
print(soup.prettify())
你可以通过标签名来查找文档中的特定元素:
python# 查找第一个 <title> 标签
title_tag = soup.title
print(title_tag)
# 查找所有 <p> 标签
p_tags = soup.find_all('p')
for p in p_tags:
print(p)
你可以轻松地访问标签的属性,比如 <a>
标签的 href
属性:
python# 查找所有的 <a> 标签
a_tags = soup.find_all('a')
for tag in a_tags:
# 打印链接文本和 href 属性
print(f"{tag.get_text()} -> {tag['href']}")
你可以根据类名或 ID 来查找特定的元素:
python# 查找所有 class="sister" 的标签
sister_tags = soup.find_all(class_='sister')
for tag in sister_tags:
print(tag)
# 查找 ID 为 "link1" 的标签
link1_tag = soup.find(id='link1')
print(link1_tag)
BeautifulSoup
提供了多种方式来遍历文档树:
python# 获取 <body> 标签下的所有直接子标签
for child in soup.body.children:
if child.name is not None: # 确保是标签而不是字符串
print(child)
# 获取 <body> 标签下的所有后代标签
for descendant in soup.body.descendants:
if descendant.name is not None:
print(descendant)
BeautifulSoup
支持 CSS 选择器语法,使查找元素更加直观:
python# 使用 CSS 选择器查找所有 class="sister" 的 <a> 标签
sister_links = soup.select('a.sister')
for link in sister_links:
print(link)
# 使用 CSS 选择器查找 ID 为 "link1" 的 <a> 标签
link1 = soup.select_one('#link1')
print(link1)
你还可以修改文档的内容、属性等:
python# 修改 <title> 标签的内容
soup.title.string = "New Title"
print(soup.title)
# 修改 <a> 标签的 href 属性
for tag in soup.find_all('a'):
tag['href'] = "https://new.example.com"
print(tag)
requests
抓取网页通常我们会结合 requests
库来抓取网页内容,然后使用 BeautifulSoup
进行解析:
pythonimport requests
from bs4 import BeautifulSoup
# 发送 GET 请求获取网页内容
url = 'https://example.com'
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 创建 BeautifulSoup 对象
soup = BeautifulSoup(response.text, 'html.parser')
# 查找所有的 <a> 标签
links = soup.find_all('a')
for link in links:
print(f"{link.get_text()} -> {link['href']}")
else:
print(f"请求失败,状态码: {response.status_code}")
在实际应用中,网络请求可能会失败,因此需要进行适当的错误处理:
pythonimport requests
from bs4 import BeautifulSoup
from requests.exceptions import RequestException
try:
url = 'https://example.com'
response = requests.get(url)
response.raise_for_status() # 如果响应状态码不是成功的代码,则引发 HTTPError 异常
soup = BeautifulSoup(response.text, 'html.parser')
# 查找所有的 <a> 标签
links = soup.find_all('a')
for link in links:
print(f"{link.get_text()} -> {link['href']}")
except RequestException as e:
print(f"请求错误: {e}")
except Exception as e:
print(f"其他错误: {e}")