T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 45 天:BeautifulSoup 爬虫:百部必看电影

这是「Python 100 天」系列第 45 天的学习笔记:BeautifulSoup 爬虫:百部必看电影。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

从一个网页抓下"史上 100 部最佳电影"的片名,倒序写进 movies.txt。README 知识点:解析 HTML、用 BeautifulSoup 查找/选择元素、抓取真实网站。

一、爬虫的三步

1
2
3
1. 取页面   requests.get(url).text
2. 解析 BeautifulSoup(html, "html.parser")
3. 提取 soup.find / find_all / select

html.parser 是标准库自带的解析器,够用;lxml 更快,需要 pip install lxml。

二、find 与 find_all

1
2
3
4
5
soup.find("h3")                        # 第一个 h3,返回 Tag 或 None
soup.find_all("h3") # 所有 h3,返回列表
soup.find(name="h3", class_="title") # 按属性找(class 是关键字,所以写成 class_)
soup.find(id="main")
soup.select("div.item > h3.title") # CSS 选择器,返回列表

两个高频坑:

  1. class_ 带下划线:class 是 Python 关键字,BeautifulSoup 用 class_ 规避。
  2. find 找不到返回 None,接着 .getText() 就是 AttributeError: 'NoneType' object has no attribute 'getText'。抓取前先确认元素存在。

三、取文本

1
2
3
tag.getText()      # 含所有子节点的文字
tag.text # 同上,更常用
tag.get("href") # 取属性

.text 常带多余空白和换行,用 .strip() 或 " ".join(s.split()) 清理。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import requests
from bs4 import BeautifulSoup

URL = "https://web.archive.org/web/20200518073855/https://www.empireonline.com/movies/features/best-movies-2/"

response = requests.get(URL)
website_html = response.text

soup = BeautifulSoup(website_html, "html.parser")

all_movies = soup.find_all(name="h3", class_="title")
movie_titles = [movie.getText() for movie in all_movies]
movies = movie_titles[::-1]

with open("movies.txt", mode="w") as file:
for movie in movies:
print(movie)
file.write(f"{movie}n")

代码走读

  1. URL 指向 web.archive.org(互联网档案馆)的快照,而不是 live 站点——因为原页面结构会变。这是爬虫项目最聪明的做法:固定一份快照,保证代码可复现。
  2. response.text 拿的是 HTML 字符串(不是 JSON)。
  3. soup.find_all(name="h3", class_="title"):抓所有标题节点。
  4. [movie.getText() for movie in all_movies]:列表推导式提取文字。
  5. movies = movie_titles[::-1]:切片反转。页面是 100→1 排列,反转成 1→100。
  6. 写文件:mode="w" 覆盖写,每行一部电影。

运行结果

movies.txt 第一行是 1: The Godfather,最后一行是 100: ...。

爬虫的规矩(必须知道)

  • 先看 robots.txt:https://站点/robots.txt 声明了哪些路径不许爬。
  • 控制频率:加 time.sleep(1),别把人家服务器打挂。
  • 别爬个人信息:邮箱、手机号、身份证,涉及《个人信息保护法》。
  • 注意版权:抓取的数据用于训练/商用可能侵权。
  • 网站改版就失效:class 名一变,find_all 返回空列表——所以爬虫要写"抓到 0 条就报警"的检查。

易错点

  1. class_="a b c":多个类名要用空格连起来,且必须完全一致。
  2. 抓到的列表为空:多半是 class 名过期,或被反爬拦了(返回的是验证码页)。
  3. 编码问题:response.encoding = "utf-8" 显式指定,避免中文乱码。
  4. getText() 带 n:写文件前 strip()。

动手改

  • 加"抓到条数不为 100 就打印警告"。
  • 用 soup.select("h3.title") 重写,对比两种写法。
  • 把结果存成 CSV(排名, 片名),为 Day 71 的 Pandas 做准备。

源文件逐个讲解

3 个文件:

文件 规模 职责
main.py19 行抓网页 → 解析 → 倒序 → 写文件
movies.txt100 行运行产物(爬取结果)
README.md9 行说明页

main.py(19 行)

1
2
3
4
import requests
from bs4 import BeautifulSoup

URL = "https://web.archive.org/web/20200518073855/https://www.empireonline.com/movies/features/best-movies-2/"

URL 里套了一层 web.archive.org(时光机):

1
2
https://web.archive.org/web/20200518073855/https://www.empireonline.com/...
└─ 2020-05-18 07:38:55 的快照

为什么要套存档? 因为原页面会变、会删、会改结构——爬虫教程必须有一个「永远不变的目标」。这是很专业的做法(教材常用 archive 固定样本)。

这行 108 字符,超过 PEP 8 的 79 字符限制——但不是错误。Day 47 用了另一种处理(字符串拼接 + 反斜杠)。

1
2
3
4
response = requests.get(URL)
website_html = response.text

soup = BeautifulSoup(website_html, "html.parser")

三行:拿 HTML → 取文本 → 造解析器。

response.text 是解码后的字符串(requests 猜编码);response.content 是原始字节。中文网站要用 content + 手动 decode,否则乱码。

"html.parser" 是 Python 内置解析器——慢但不用装依赖。生产环境用 "lxml"(快 5~10 倍)。

1
2
3
all_movies = soup.find_all(name="h3", class_="title")
movie_titles = [movie.getText() for movie in all_movies]
movies = movie_titles[::-1]

这是全篇最核心的三行:

(1)find_all(name="h3", class_="title")

注意 class_ 的下划线:class 是 Python 关键字,BeautifulSoup 用 class_ 避开冲突。写 class="title" 会 SyntaxError——这是初学者最常撞的墙。

(2)[movie.getText() for movie in all_movies]

getText() 提取标签内的纯文本(去掉 <h3> 标签本身)。新版也可以写 .text。

(3)[::-1] 倒序

因为原页面是「100 → 1」倒着排的,作者想要「1 → 100」,所以切片反转。这一步是「数据清洗」——爬虫拿到的数据几乎总要整理。

1
2
3
4
with open("movies.txt", mode="w") as file:
for movie in movies:
print(movie)
file.write(f"{movie}n")

with open(...) 上下文管理器:退出时自动关闭文件(即使中间抛异常)。

mode="w" 是覆盖写——每次运行都会把 movies.txt 冲掉重写。想追加要用 "a"。

f"{movie}n" 手动加换行:file.write 不会自动换行(对比 print 会自动加)。

print(movie) 和 file.write 并列:屏幕看一遍、文件存一份。调试完应该删掉 print。

movies.txt(100 行)——注意读这个文件

它不只是「输出」,还是「证据」:从这份文件能看出源网页的数据长什么样。

(1)编号格式不统一

1
2
3
1) The Godfather
...
12: The Godfather Part II

第 12 行用的是冒号 12:,其余都是 12)——这是源网页自己的排版问题,爬虫原样搬过来了。

(2)第 80 行是 15) Spirited Away

1
2
3
79) Captain America: Civil War
15) Spirited Away
81) The Social Network

《千与千寻》的编号被写成了 15)——源页面的编辑错误(可能是模板里复制了别的条目)。爬虫无法发现这种错,因为它只认 class="title"。

这告诉我们一件事:爬下来的数据 ≠ 正确数据。真实的数据管道必须有「校验/清洗」环节。

(3)条目里有特殊字符

1
2
3
59) E.T. – The Extra Terrestrial
85) Léon
69) Singin' In The Rain

–(en dash)、é、' 都被正确写入了——因为 open() 用了默认编码(macOS/Linux 是 UTF-8)。

在 Windows 上默认是 GBK,写 é 会 UnicodeEncodeError。这就是为什么规范代码要写 encoding="utf-8"——这份代码没写,是个隐患。

这份代码的问题

  1. open() 没指定 encoding="utf-8"(Windows 会崩)。
  2. requests.get 没有 timeout:网络卡住会一直等。
  3. 没有检查 response.status_code:404 页面也会被解析,结果为空。
  4. 没有 User-Agent:有些站会 403(Day 47 就加了)。
  5. print 和 write 混在一起,正式脚本应分开。
  6. movies.txt 里保留了源站编号错误,没做清洗。

README.md(9 行)

标题 Day 45 - Web Scraping with Beautiful Soup,知识点:Parsing HTML、Beautiful Soup、Scraping a Live Website。

三条:解析 HTML、用 BS4、爬真实网站。这是全书「爬虫」的起点——后面 Day 46/47/92 都是它的变体。

微信收款码 微信
支付宝收款码 支付宝
评论