Beautiful Soup 的详细使用指南,涵盖安装、解析、元素查找及常见场景示例:
1. 安装
bash
pip install beautifulsoup4
# 建议搭配解析器(如 lxml 或 html.parser)
pip install lxml2. 基础用法
解析 HTML
python
from bs4 import BeautifulSoup
import requests
# 获取网页内容
response = requests.get("https://example.com")
html = response.text
# 创建 Beautiful Soup 对象(推荐使用 lxml 解析器)
soup = BeautifulSoup(html, "lxml")
# 获取标题
title = soup.title.text
print(title) # "Example Domain"3. 查找元素
通过标签名查找
python
# 查找第一个 <p> 标签
first_p = soup.p
print(first_p.text)
# 查找所有 <a> 标签
all_links = soup.find_all("a")
for link in all_links:
print(link.get("href"))通过属性查找
python
# 查找 class 为 "header" 的 div
header = soup.find("div", class_="header")
# 查找 id 为 "main" 的标签
main_content = soup.find(id="main")
# 组合条件(如同时匹配标签和属性)
button = soup.find("button", {"type": "submit"})4. 提取数据
获取文本
python
# 获取标签内的文本(自动去除子标签)
text = soup.find("h1").get_text()
# 获取所有直接子文本(含空白符)
raw_text = soup.find("div").strings
for string in raw_text:
print(repr(string)) # 包含换行符等获取属性值
python
# 获取 href 属性
link = soup.find("a")
url = link["href"] # 或 link.get("href")5. 层级导航
父子节点
python
# 获取父节点
parent = link.parent
# 获取直接子节点
children = list(soup.div.children) # 含换行符等兄弟节点
python
# 下一个兄弟节点
next_sibling = soup.p.next_sibling
# 上一个兄弟节点
previous_sibling = soup.p.previous_sibling6. 高级查找(CSS 选择器)
python
# 选择类名为 "item" 的所有 div
items = soup.select("div.item")
# 选择 id 为 "footer" 的标签
footer = soup.select_one("#footer")
# 嵌套选择
links_in_nav = soup.select("nav ul li a")7. 处理复杂结构
表格数据提取
python
table = soup.find("table")
rows = table.find_all("tr")
for row in rows:
columns = row.find_all("td")
data = [col.text.strip() for col in columns]
print(data)处理嵌套标签
python
article = soup.find("article")
for paragraph in article.find_all("p"):
if paragraph.find("img"):
print("包含图片的段落:", paragraph.text)8. 与 Requests 结合实战
场景:爬取新闻标题和链接
python
url = "https://news.example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "lxml")
news_list = []
for article in soup.select(".news-article"):
title = article.find("h2").text.strip()
link = article.find("a")["href"]
news_list.append({"title": title, "link": link})
print(news_list)9. 常见问题
编码问题:
- 指定响应编码:
response.encoding = "utf-8" - 使用
soup.prettify()格式化输出。
- 指定响应编码:
动态内容:
- Beautiful Soup 仅解析静态 HTML。若页面由 JavaScript 动态加载,需结合 Selenium 或 Playwright。
性能优化:
- 对大型文档使用
lxml解析器(速度更快)。 - 减少不必要的遍历(优先使用 CSS 选择器)。
- 对大型文档使用
10. 完整示例
python
import requests
from bs4 import BeautifulSoup
def scrape_quotes():
url = "http://quotes.toscrape.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "lxml")
quotes = []
for quote_div in soup.select("div.quote"):
text = quote_div.find("span", class_="text").text
author = quote_div.find("small", class_="author").text
tags = [tag.text for tag in quote_div.select("a.tag")]
quotes.append({"text": text, "author": author, "tags": tags})
return quotes
if __name__ == "__main__":
quotes = scrape_quotes()
for quote in quotes[:3]:
print(quote)通过 Beautiful Soup,可以高效解析 HTML/XML 内容,适用于数据抓取、内容分析等场景。对于复杂需求,建议搭配 Requests(网络请求)和 Pandas(数据处理)使用。