Python 自动化运维与爬虫 · 篇2 · 入门级
← 上篇:网络请求基础:Requests库入门   |   下篇:进阶爬虫:Scrapy框架与动态页面 →

网页解析:BeautifulSoup与数据提取

从HTML到结构化数据,掌握精准提取的艺术
用 Requests 拿到了网页的 HTML 源码,但这只是一堆标签和文字——我们真正需要的是其中结构化的数据:商品名称、价格、评分、链接等。BeautifulSoup 就是干这件事的:它把凌乱的 HTML 解析成一棵干净的 DOM 树,让你像查字典一样精准提取任何信息。本文将从 HTML 基础讲起,系统讲解 BeautifulSoup 的各种用法,最后实战爬取豆瓣电影 Top250。
目录
01HTML结构回顾
02BeautifulSoup安装与解析器选择
03find与find_all:按标签、属性、CSS类查找
04CSS选择器:select方法
05提取文本与属性
06DOM树导航:parent、children、siblings
07正则表达式辅助提取
08表格数据提取
09实战:爬取豆瓣电影Top250
10爬虫道德:robots.txt与请求频率

01 · HTML结构回顾

HTML(超文本标记语言)是网页的骨架,它由嵌套的标签组成一棵树形结构。要高效地使用 BeautifulSoup 提取数据,首先要理解 HTML 的基本构成。

HTML 典型HTML结构
<!-- 一段典型的商品列表HTML -->
<div class="product-list">
  <div class="product-card" data-id="1001">
    <h2 class="title">Python编程入门</h2>
    <span class="price">89.00</span>
    <a href="/product/1001">查看详情</a>
  </div>
</div>

HTML 的三个核心概念:标签(Tag)是元素类型,如 <div>、<a>;属性(Attribute)是标签的附加信息,如 class、href、id;DOM 树是标签的嵌套关系,形成父子层级结构。在爬虫中,我们就是通过这些标签和属性来定位目标数据的。

02 · BeautifulSoup安装与解析器选择

安装 BeautifulSoup 和推荐的解析器 lxml:

Shell 安装命令
pip install beautifulsoup4 lxml html5lib

BeautifulSoup 支持多种解析器,它们的性能和对 HTML 的容错能力各有不同:

解析器 速度 容错能力 是否需要安装
html.parser 中等 较好 内置,无需安装
lxml ⭐最快 好 需 pip install lxml
html5lib 慢 ⭐最好(与浏览器一致) 需 pip install html5lib
💡 小贴士:如何选择解析器
日常爬虫推荐使用 lxml——速度快且容错不错。如果目标网页 HTML 非常不规范(标签未闭合等),可以换用 html5lib,它按浏览器的方式解析 HTML,容错能力最强。
Python 创建BeautifulSoup对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from bs4 import BeautifulSoup
import requests

# 从HTML字符串创建
html = "<h1>Hello</h1><p>World</p>"
soup = BeautifulSoup(html, "lxml")

# 从网络请求创建(最常见)
resp = requests.get("https://example.com")
soup = BeautifulSoup(resp.text, "lxml")

# 从本地文件创建
with open("page.html", "r", encoding="utf-8") as f:
soup = BeautifulSoup(f, "lxml")

03 · find与find_all:按标签、属性、CSS类查找

find() 返回第一个匹配的元素,find_all() 返回所有匹配元素的列表。这两个方法是最基础、最常用的查找方法。

Python find与find_all详解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from bs4 import BeautifulSoup

html = """
<div class="book-list">
<div class="book-item" data-category="tech">
<h3 class="title">Python从入门到放弃</h3>
<span class="price">69.00</span>
<span class="rating">4.5</span>
</div>
<div class="book-item" data-category="fiction">
<h3 class="title">三体</h3>
<span class="price">45.00</span>
<span class="rating">9.4</span>
</div>
<div class="book-item" data-category="tech">
<h3 class="title">机器学习实战</h3>
<span class="price">99.00</span>
<span class="rating">8.8</span>
</div>
</div>
"""
soup = BeautifulSoup(html, "lxml")

# 1. 按标签查找
first_h3 = soup.find("h3") # 返回第一个h3
all_h3 = soup.find_all("h3") # 返回所有h3列表
print(f"第一本书: {first_h3.text}")
print(f"共 {len(all_h3)} 本书")

# 2. 按CSS类查找(注意:class是Python保留字)
titles = soup.find_all("h3", class_="title")
prices = soup.find_all("span", class_="price")

# 3. 按属性查找
tech_books = soup.find_all(
"div", attrs={"data-category": "tech"}
)
print(f"技术类图书: {len(tech_books)} 本")

# 4. 限制返回数量
top2 = soup.find_all("div", class_="book-item", limit=2)
⚠️ 常见错误
使用 find() 时,如果没找到匹配元素,返回的是 None 而不是抛出异常。后续对 None 调用 .text 或属性访问会导致 AttributeError。建议在访问属性前先检查:if element is not None。

04 · CSS选择器:select方法

如果你熟悉 CSS,可以直接用 CSS 选择器语法来查找元素——这在复杂定位场景下比 find_all 更简洁。使用 select() 返回所有匹配,select_one() 返回第一个匹配。

选择器 含义 示例
tag 标签名 select("h3")
.class CSS类名 select(".title")
#id 元素ID select("#main")
tag.class 标签+类 select("span.price")
A B A内的B(后代) select(".book-list h3")
A > B A的直接子元素B select("div > h3")
[attr=val] 属性等于值 select('[data-category="tech"]')

05 · 提取文本与属性

找到元素后,下一步就是提取其中的文本和属性值。BeautifulSoup 提供了多种提取方式:

Python 文本与属性提取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from bs4 import BeautifulSoup

html = """
<a href="/product/1001" class="link" title="查看详情">
<strong>Python编程</strong> - 限时特价
</a>
"""
soup = BeautifulSoup(html, "lxml")
link = soup.find("a")

# 提取文本
print(link.text) # "Python编程 - 限时特价"(含子标签文本)
print(link.get_text()) # 同上
print(link.get_text(strip=True)) # 去除两端空白
print(link.get_text(separator=" | ")) # "Python编程 | - 限时特价"

# 提取属性
print(link["href"]) # "/product/1001"
print(link.get("href")) # 同上,但不存在时返回None(更安全)
print(link["title"]) # "查看详情"
print(link["class"]) # ["link"](注意:返回的是列表!)

# 获取所有属性
print(link.attrs) # {'href': '/product/1001', 'class': ['link'], ...}
💡 小贴士:text vs get_text()
.text 和 .get_text() 效果基本相同,但 get_text() 支持更多参数,比如 strip=True 去除空白、separator 指定分隔符。推荐在需要清理文本时使用 get_text()。

06 · DOM树导航:parent、children、siblings

有时候你已经找到了某个元素,但需要的数据在它的相关节点中。BeautifulSoup 提供了在 DOM 树中自由导航的方法:

Python DOM树导航
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from bs4 import BeautifulSoup

html = """
<ul id="menu">
<li class="active">首页</li>
<li>产品</li>
<li>关于我们</li>
</ul>
"""
soup = BeautifulSoup(html, "lxml")
active = soup.find("li", class_="active")

# 向上导航:找父元素
parent = active.parent
print(f"父元素标签: {parent.name}") # "ul"
print(f"父元素ID: {parent['id']}") # "menu"

# 向下导航:遍历子元素
for child in parent.children:
if child.name: # 跳过空白文本节点
print(f" 子元素: {child.text}")

# 横向导航:找兄弟元素
next_li = active.find_next_sibling()
prev_li = active.find_previous_sibling()
print(f"下一个兄弟: {next_li.text}") # "产品"
print(f"上一个兄弟: {prev_li}") # None(已经是第一个)

# 获取所有兄弟
all_siblings = active.find_next_siblings()
print(f"后续兄弟数: {len(all_siblings)}") # 2

07 · 正则表达式辅助提取

当 HTML 结构不够规范,或者需要从文本中提取特定模式的数据时,可以将正则表达式与 BeautifulSoup 结合使用:

Python 正则表达式+BeautifulSoup
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import re
from bs4 import BeautifulSoup

html = """
<div class="info">
<p>联系电话:010-12345678</p>
<p>邮箱:admin@example.com</p>
<p>地址:北京市海淀区中关村大街1号</p>
</div>
"""
soup = BeautifulSoup(html, "lxml")

# 用正则表达式在find中匹配标签文本
phone_tag = soup.find("p", string=re.compile(r"联系电话"))
print(phone_tag.text)

# 从文本中提取结构化数据
text = phone_tag.text
phone = re.search(r"(\d{3}-\d{8})", text)
if phone:
print(f"电话号码: {phone.group(1)}")

# 用正则匹配属性值
links = soup.find_all("a", href=re.compile(r"^/product/\d+$"))

08 · 表格数据提取

表格是网页中非常常见的数据载体。从 HTML 表格中提取数据是爬虫的高频需求:

Python 表格数据提取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from bs4 import BeautifulSoup

html = """
<table id="scores">
<thead>
<tr><th>姓名</th><th>语文</th><th>数学</th></tr>
</thead>
<tbody>
<tr><td>张三</td><td>85</td><td>92</td></tr>
<tr><td>李四</td><td>90</td><td>88</td></tr>
<tr><td>王五</td><td>78</td><td>95</td></tr>
</tbody>
</table>
"""
soup = BeautifulSoup(html, "lxml")
table = soup.find("table", id="scores")

# 提取表头
headers = []
for th in table.find_all("th"):
headers.append(th.get_text(strip=True))

# 提取数据行
rows = []
for tr in table.find("tbody").find_all("tr"):
cells = [td.get_text(strip=True) for td in tr.find_all("td")]
rows.append(cells)

# 转为字典列表
data = [dict(zip(headers, row)) for row in rows]
for item in data:
print(item)
# {'姓名': '张三', '语文': '85', '数学': '92'}
# {'姓名': '李四', '语文': '90', '数学': '88'}
# {'姓名': '王五', '语文': '78', '数学': '95'}

09 · 实战:爬取豆瓣电影Top250

让我们把前面学到的所有知识整合起来,编写一个完整的爬虫程序——爬取豆瓣电影 Top250 榜单。这个榜单分布在 10 个页面中,每页 25 部电影。我们需要提取电影名称、评分、评价人数、一句话描述等信息。

⚠️ 注意事项
豆瓣对爬虫有一定的反爬措施。运行代码时必须设置合理的 User-Agent 和请求间隔。以下代码仅供学习参考,请遵守 robots.txt 协议,不要高频请求。
Python 完整实战:豆瓣Top250爬虫
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import requests
from bs4 import BeautifulSoup
import time
import csv

def get_page(url, headers):
"""获取页面HTML内容"""
try:
resp = requests.get(url, headers=headers, timeout=10)
resp.raise_for_status()
return resp.text
except requests.RequestException as e:
print(f"请求失败: {e}")
return None

def parse_movies(html):
"""从HTML中解析电影信息"""
soup = BeautifulSoup(html, "lxml")
movies = []
# 每部电影在一个 ol > li 中
items = soup.select("ol.grid_view > li")
for item in items:
# 排名
rank = item.select_one(".pic em").get_text()
# 电影名称(中文名)
title = item.select_one(".hd a .title").get_text()
# 评分
rating = item.select_one(".rating_num").get_text()
# 评价人数
people = item.select_one(".star span:last-child")
people_text = people.get_text() if people else "0"
# 一句话描述(inq,部分电影没有)
quote_tag = item.select_one(".inq")
quote = quote_tag.get_text() if quote_tag else ""
# 详情链接
link = item.select_one(".hd a")["href"]
movies.append({
"排名": rank,
"电影名": title,
"评分": rating,
"评价人数": people_text,
"一句话": quote,
"链接": link
})
return movies

def main():
"""主函数:爬取Top250并保存为CSV"""
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36",
"Accept-Language": "zh-CN,zh;q=0.9"
}
all_movies = []
base_url = "https://movie.douban.com/top250"
# 共10页,每页25部
for page in range(10):
start = page * 25
url = f"{base_url}?start={start}&filter="
print(f"正在爬取第 {page + 1} 页...")
html = get_page(url, headers)
if html:
movies = parse_movies(html)
all_movies.extend(movies)
print(f" 获取到 {len(movies)} 部电影")
# 礼貌地等待,避免请求过快
time.sleep(2)
# 保存为CSV文件
if all_movies:
with open("douban_top250.csv", "w",
encoding="utf-8-sig", newline="") as f:
writer = csv.DictWriter(
f, fieldnames=all_movies[0].keys()
)
writer.writeheader()
writer.writerows(all_movies)
print(f"\n完成!共获取 {len(all_movies)} 部电影")
print("数据已保存到 douban_top250.csv")

if __name__ == "__main__":
main()

这段代码展示了爬虫的典型流程:请求 → 解析 → 存储。注意其中几个关键细节:使用 time.sleep(2) 控制请求频率,使用 utf-8-sig 编码确保 CSV 在 Excel 中正确显示中文,以及对可选字段(如"一句话")做了 None 检查。

10 · 爬虫道德:robots.txt与请求频率

编写爬虫不仅要关注技术实现,还要遵守基本的道德规范和法律要求。

robots.txt 协议

大多数网站会在根目录放置 robots.txt 文件,声明哪些路径允许爬虫访问。例如 https://example.com/robots.txt。虽然 robots.txt 不是强制性的,但遵守它是爬虫的基本礼仪。

请求频率控制

高频请求会对目标服务器造成压力,甚至被视为恶意攻击。建议:

💡 爬虫最佳实践
1. 每次请求间隔至少 1-2 秒
2. 设置合理的 User-Agent,表明身份
3. 只爬取公开可访问的数据
4. 不要爬取个人隐私信息
5. 遵守目标网站的使用条款
6. 如有官方 API 可用,优先使用 API
📋 本篇知识回顾
HTML/DOM结构 解析器选择 find/find_all CSS选择器select 文本与属性提取 DOM树导航 正则表达式辅助 表格数据提取 豆瓣Top250实战 爬虫道德规范
下一篇预告
03 · 进阶爬虫:Scrapy框架与动态页面
当你需要爬取大量页面或处理 JavaScript 动态渲染的网站时,BeautifulSoup + Requests 的组合就显得力不从心了。下一篇我们将学习专业的爬虫框架 Scrapy,以及浏览器自动化工具 Playwright,让你能应对更复杂的爬虫场景。
相关阅读
想动手实操?你需要一台服务器
学编程离不开动手实操。一台入门级云服务器是你最好的练习场,数据库、对象存储、CDN、短信也都能用上,入门配置很便宜,够你把学到的东西真跑一遍。
查看腾讯云优惠查看阿里云优惠
想系统入门?配一本书
看文章学的是零散知识点,想系统入门还得有一本书打底。
Python 入门书C 与 Python 入门Web 开发书