第 43 课 · 阶段八 · 项目实战

网络爬虫入门

爬虫 = 用代码替你去网页上“复制粘贴数据”。这一课从 requests 下载网页开始,带你写完人生第一个爬虫,并讲清 robots 与道德边界。

第 43 课阶段八 · 项目实战难度:进阶建议时长:45 分钟关键词:requests · 爬取 · 解析 · 反爬

🎯 学完本课你将掌握

  • 理解爬虫的基本流程
  • 用 requests 获取网页内容
  • 用 BeautifulSoup 解析并提取数据
  • 了解反爬与合规边界

一、爬虫三步曲

  1. 1
    发送请求:用 requests 向网址发请求,拿到网页 HTML。
  2. 2
    解析内容:用 BeautifulSoup 从 HTML 里提取想要的数据。
  3. 3
    保存数据:把结果存到列表、文件或 JSON 里。

二、安装库

安装依赖
1pip install requests beautifulsoup4

三、第一步:用 requests 获取网页

获取网页.py
1import requests
2
3url = "https://example.com"
4resp = requests.get(url)
5print(resp.status_code) # 200 表示成功
6print(resp.encoding) # 编码
7print(resp.text[:300]) # 网页源码前300字符
✅ 要点
status_code 200 成功、404 页面不存在、403 无权限(常被反爬)。

四、伪装请求头

很多网站会检查 User-Agent,带上浏览器标识更像真人访问。

带请求头.py
1import requests
2headers = {
3 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
4}
5resp = requests.get("https://example.com", headers=headers, timeout=10)
6print(resp.status_code)

五、用 BeautifulSoup 解析

解析网页.py
1from bs4 import BeautifulSoup
2
3html = "<h1>标题</h1><p class='price'>99</p><a href='https://x.com'>链接</a>"
4soup = BeautifulSoup(html, "html.parser")
5
6print(soup.h1.text) # 标题 找第一个 h1
7print(soup.select_one(".price").text) # 99 按 class 找
8print(soup.find("a")["href"]) # https://x.com 取属性

六、实战:抓取一个示例站点

小爬虫.py
1import requests
2from bs4 import BeautifulSoup
3
4url = "https://example.com"
5headers = {"User-Agent": "Mozilla/5.0"}
6resp = requests.get(url, headers=headers, timeout=10)
7
8soup = BeautifulSoup(resp.text, "html.parser")
9for h in soup.find_all("h1"):
10 print("找到标题:", h.text.strip())

七、反爬与合规(务必牢记)

⚠️ 注意
爬虫有边界:① 只爬公开数据,不碰需要登录的私人数据;② 尊重 robots.txt 与网站声明;③ 控制请求频率,不要打爆服务器;④ 遵守《网络安全法》《数据安全法》,不得用于牟利侵权。做练习请用公开测试网站。

八、常见错误与解决

常见错误与解决

错误现象原因 / 解决方法
403 Forbidden被反爬拦截,加 User-Agent、Cookie,或降低频率重试。
requests.exceptions.ConnectionError网络不通或域名错误,检查 URL 与网络。
解析出空列表选择器写错或页面是动态渲染(数据在 JS 里),改用接口地址或 Selenium。
✍️ 小练习
写一个爬虫抓取 https://example.com 的标题并打印;再试着解析一段带表格的 HTML,提取表格所有单元格文本。
📌 本节小结
爬虫三步:requests 拿 HTML → BeautifulSoup 解析 → 提取保存。一定要带请求头、控制频率,并遵守 robots 与法律。学完它,获取公开数据的能力就解锁了。