欢迎来到第五期!从这一期开始,我们的教程将从"学语法"转向"做项目"。
经过前面四期的积累,你已经掌握了 Python 的基础语法、数据结构、面向对象和装饰器/生成器。现在,我们要用这些知识来做一件有趣的事情 —— **写爬虫**。
爬虫,英文叫 Web Scraper,本质上就是一个自动从网页上抓取数据的程序。不管是商品价格、天气数据、还是某篇新闻的全文,只要你能在浏览器上看到它,Python 就能帮你抓下来。
>**⚠️ 重要提醒**:使用爬虫时请遵守法律法规和网站的 robots.txt 协议,不抓取敏感数据,不用于商业侵权。本教程仅用于学习和技术交流。
---
## 5.1 爬虫的核心原理
先理解一件事:**爬虫就是在模拟浏览器**。
当你在浏览器里访问百度时,发生了什么?
1. 你的浏览器向百度的服务器发送一个 HTTP 请求
2. 百度返回一个 HTML 页面
3. 浏览器解析 HTML 并渲染出你看到的样子
爬虫做的也是同样的事:发送请求 → 接收 HTML → 解析提取数据。只不过我们不用浏览器,而是用 Python 代码来完成这三个步骤。
### 核心工具
| 工具 | 作用 |
|------|------|
| `requests` | 发送 HTTP 请求,获取网页 HTML |
| `BeautifulSoup` | 解析 HTML,提取你想抓取的元素 |
| `re` (正则表达式) | 处理非结构化的文本数据 |
| `csv` / `json` | 保存抓取到的数据 |
---
## 5.2 环境准备
安装两个核心库:
```bash
pipinstallrequestsbeautifulsoup4lxml
```
`lxml` 是 BeautifulSoup 的一个快速解析器,安装后会让解析速度显著提升。
---
## 5.3 第一步:用 requests 获取网页
### 5.3.1 发送 GET 请求
最简单的爬虫就是发一个 GET 请求:
```python
import requests
# 抓取知乎首页
url = "https://www.zhihu.com"
response = requests.get(url)
# 查看状态码
print(f"HTTP 状态码: {response.status_code}") # 200 表示成功
# 查看响应内容
print(response.text[:500]) # 打印前 500 个字符
```
**输出**:
```
HTTP 状态码: 200
<!DOCTYPE html><html lang="zh-CN"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-user-scalable=no"...
```
>**注意**:知乎等大厂网站有反爬机制,直接请求可能返回登录页。我们用一些开放的测试网站来练习。
### 5.3.2 设置请求头(Headers)
很多网站会检查你是什么浏览器,如果识别到是 Python 脚本就可能拒绝你。所以我们需要"伪装":
```python
import requests
url = "https://httpbin.org/get"# 这是一个测试网站,会返回你发送的请求信息
# 模拟浏览器的请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}
response = requests.get(url, headers=headers)
print(response.json())
```
三个实用技巧:
1.**User-Agent**:告诉服务器"我是浏览器,不是机器人"
2.**Cookies**:如果网站需要你登录才能看某些内容,带上 cookie
3.**超时设置**:设置 timeout 防止请求卡死
```python
# 更稳健的请求方式
response = requests.get(
url,
headers=headers,
timeout=10, # 10秒超时
verify=True# 验证 SSL 证书(HTTPS 网站)
)
```
### 5.3.3 发送 POST 请求
有些数据需要通过 POST 请求才能获取,比如表单提交、搜索查询:
```python
import requests
url = "https://httpbin.org/post"
payload = {
"username": "test_user",
"search_keyword": "Python爬虫",
}
response = requests.post(url, data=payload, headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
})
print(response.json()["form"]) # 查看服务端收到的表单数据
# {'username': 'test_user', 'search_keyword': 'Python爬虫'}
```
---
## 5.4 第二步:用 BeautifulSoup 解析网页
拿到 HTML 只是第一步,真正有价值的是从 HTML 中提取你想要的东西。这就是 BeautifulSoup 的工作。
### 5.4.1 基本用法
找一个适合练习的网页。我们用 httpbin.org 和一个常见的测试页面:
```python
import requests
from bs4 import BeautifulSoup
# 使用一个包含丰富 HTML 元素的测试页面
url = "https://quotes.toscrape.com"# 专门用于练习爬虫的开放网站
response = requests.get(url, headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
})
# 创建 BeautifulSoup 对象
soup = BeautifulSoup(response.text, "lxml")
# 查找页面上所有的名言引用
quotes = soup.find_all("div", class_="quote")
for i, quote inenumerate(quotes, 1):
text = quote.find("span", class_="text").get_text()
author = quote.find("small", class_="author").get_text()
tags = quote.find_all("a", class_="tag")
tag_list = [tag.get_text() for tag in tags]
print(f"{i}. \"{text}\" — {author}")
print(f" 标签: {', '.join(tag_list)}")
print()
```
**输出**:
```
1. "The world as we have created it is a process of our thinking. It is a
change of a moment." — Albert Einstein
标签: change, deep-thoughts, thinking, world
2. "It is our choices, Harry, that show what we truly are, far more than
our abilities." — J.K. Rowling
标签: choices, abilities
3. "There are only two ways to live your life. One is as though nothing
is a miracle. The other is as though everything is a miracle." —
Albert Einstein
标签: inspirational, life, live, miracle, choices
```
### 5.4.2 BeautifulSoup 的查找方法速查
| 方法 | 说明 | 示例 |
|------|------|------|
| `find()` | 找第一个匹配的元素 | `soup.find("h1")` |
| `find_all()` | 找所有匹配的元素 | `soup.find_all("p")` |
| `select()` | CSS 选择器,最强大 | `soup.select("div.content > h2.title")` |
| `get_text()` | 获取纯文本 | `element.get_text(strip=True)` |
| `.attr` | 获取属性值 | `element["href"]` |
```python
# CSS 选择器示例(推荐,功能最强大)
# 假设 HTML 结构如下:
# <div class="article">
# <h2 class="title">Python 爬虫教程</h2>
# <p class="meta">作者: 小明 | 发布于 2026-07-03</p>
# <div class="content">正文内容...</div>
# </div>
items = soup.select("div.article") # 找到所有 article div
for item in items:
title = item.select_one(".title").get_text(strip=True)
meta = item.select_one(".meta").get_text(strip=True)
content = item.select_one(".content").get_text(strip=True)
print(f"标题: {title}")
print(f"元信息: {meta}")
print(f"内容: {content[:100]}...")
print()
```
### 5.4.3 实战:抓取豆瓣电影 Top 250
让我们做一个真正的实战项目。
```python
import requests
from bs4 import BeautifulSoup
import csv
defscrape_douban_top250():
"""
抓取豆瓣电影 Top 250 榜单
URL: https://movie.douban.com/top250
每页展示 25 部电影,共 10 页
"""
all_movies = []
base_url = "https://movie.douban.com/top250"
# 模拟浏览器请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Accept-Language": "zh-CN,zh;q=0.9",
}
for page inrange(10): # 共 10 页
start = page * 25# 起始偏移量 (0, 25, 50, ..., 225)
url = f"{base_url}?start={start}&filter="
print(f"正在抓取第 {page + 1} 页...")
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status() # 如果不是 200,抛出异常
except requests.RequestException as e:
print(f"抓取失败: {e}")
continue
soup = BeautifulSoup(response.text, "lxml")
items = soup.select("ol.grid_view li")
for item in items:
movie = {}
movie["rank"] = item.select_one(".rating_qty").get_text()
movie["name"] = item.select_one(".hd a span").get_text(strip=True)
movie["rating"] = item.select_one(".rating_num").get_text()
movie["url"] = item.select_one(".hd a")["href"]
# 尝试获取简介(可能不存在)
desc_el = item.select_one(".inq")
movie["short_comment"] = desc_el.get_text() if desc_el else"暂无短评"
all_movies.append(movie)
return all_movies
defsave_to_csv(movies, filename="douban_top250.csv"):
"""将抓取的數據保存为 CSV 文件"""
ifnot movies:
print("没有数据可保存!")
return
withopen(filename, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=["rank", "name", "rating", "url", "short_comment"])
writer.writeheader()
writer.writerows(movies)
print(f"\n成功保存 {len(movies)} 部电影到 {filename}")
# 运行
movies = scrape_douban_top250()
save_to_csv(movies)
# 打印结果预览
print("\n=== 豆瓣电影 Top 250 结果预览 ===")
for m in movies[:5]:
print(f"#{m['rank']}{m['name']} 评分: {m['rating']}{m['short_comment']}")
```
>**提示**:豆瓣有较强的反爬机制,频繁抓取可能被封 IP。建议在学习时加 `time.sleep(3)` 休眠几秒。实际生产中需要用代理池和更温和的策略。
---
## 5.5 反爬策略与应对
### 5.5.1 常见的反爬手段
| 反爬方式 | 说明 | 应对策略 |
|---------|------|---------|
| 检查 User-Agent | 识别是否为浏览器请求 | 设置合理的 UA |
| IP 频率限制 | 短时间内请求过多封 IP | 控制抓取速度、使用代理 |
| 验证码 | CAPTCHA 验证 | 打码平台 / 避免触发 |
| JavaScript 渲染 | 关键内容由 JS 动态生成 | 使用 Selenium / Playwright |
| Cookie 校验 | 要求携带特定 Cookie | 先访问首页获取 Cookie |
| Token 验证 | 接口需要动态 token | 分析 JS 逆向提取 |
### 5.5.2 最佳实践
```python
import requests
from bs4 import BeautifulSoup
import time
import random
classSmartScraper:
"""
智能爬虫类 —— 封装了常用的反爬应对策略
这是我们在实战中总结的一套模板
"""
def__init__(self, delay_range=(1, 3)):
self.delay_range = delay_range
self.session = requests.Session()
self.session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
})
def_wait(self):
"""随机延迟,模拟人类操作节奏"""
delay = random.uniform(*self.delay_range)
time.sleep(delay)
defget(self, url, **kwargs):
"""发送 GET 请求,带重试机制"""
for attempt inrange(3): # 最多重试 3 次
try:
self._wait()
response = self.session.get(url, timeout=10, **kwargs)
response.raise_for_status()
return response
except requests.exceptions.RequestException as e:
print(f" [重试 {attempt + 1}/3] 请求出错: {e}")
time.sleep(2 ** attempt) # 指数退避
print(f" [失败] 重试 3 次后仍然失败: {url}")
returnNone
defscrape_page(self, url):
"""抓取并解析一个页面"""
response = self.get(url)
if response isNone:
returnNone
soup = BeautifulSoup(response.text, "lxml")
return soup
defsave_html(self, html_content, filename):
"""将原始 HTML 保存到文件,方便调试"""
withopen(filename, "w", encoding="utf-8") as f:
f.write(html_content)
print(f" HTML 已保存到 {filename}")
# 使用示例
scraper = SmartScraper(delay_range=(2, 5)) # 2~5秒随机延迟
soup = scraper.scrape_page("https://quotes.toscrape.com")
if soup:
quotes = soup.select("div.quote")
for quote in quotes[:3]:
text = quote.select_one("span.text").get_text(strip=True)
author = quote.select_one("small.author").get_text(strip=True)
print(f"「{text}」— {author}")
```
这个 `SmartScraper` 类封装了几个关键的反爬策略:
1.**Session 复用**:同一个 session 自动管理 cookies
2.**随机延迟**:2~5 秒的随机等待,避免过于规律
3.**指数退避**:出错时逐步增加等待时间
4.**HTML 保存**:便于调试和分析页面结构
---
## 5.6 进阶:处理动态加载页面
有些网站的内容是通过 JavaScript 动态加载的,requests + BeautifulSoup 只能拿到空壳。这时需要用到**浏览器自动化工具**。
### 5.6.1 用 Selenium 抓取动态页面
```python
# pip install selenium webdriver-manager
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
defscrape_dynamic_page(url):
"""
使用 Selenium 抓取 JavaScript 动态渲染的页面
"""
options = Options()
options.add_argument("--headless") # 无头模式,不显示浏览器窗口
options.add_argument("--disable-gpu")
options.add_argument(
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
)
driver = webdriver.Chrome(options=options)
driver.get(url)
# 等待页面加载(简单粗暴的 sleep,生产环境用 WebDriverWait)
import time
time.sleep(3)
# 获取渲染后的 HTML
html = driver.page_source
driver.quit()
# 用 BeautifulSoup 解析
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "lxml")
return soup
# 使用
soup = scrape_dynamic_page("https://quotes.toscrape.com/js/")
quotes = soup.select("div.quote")
for q in quotes[:3]:
print(q.select_one("span.text").get_text(strip=True))
```
### 5.6.2 更现代的选择:Playwright
Playwright 是微软开发的新一代浏览器自动化框架,比 Selenium 更快、更简单:
```python
# pip install playwright && playwright install
from playwright.sync_api import sync_playwright
defscrape_with_playwright(url):
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto(url)
page.wait_for_selector(".quote")
quotes = []
for item in page.query_selector_all(".quote"):
text = item.query_selector("span.text").inner_text()
author = item.query_selector("small.author").inner_text()
quotes.append({"text": text, "author": author})
browser.close()
return quotes
results = scrape_with_playwright("https://quotes.toscrape.com/js/")
for r in results[:3]:
print(f"{r['text']} — {r['author']}")
```
---
## 5.7 实战项目:简易新闻聚合器
综合运用以上知识,写一个完整的新闻聚合小工具:
```python
import requests
from bs4 import BeautifulSoup
import csv
import time
import random
from datetime import datetime
classNewsAggregator:
"""
简易新闻聚合器
从多个来源抓取新闻标题、链接和发布时间,保存为 CSV
"""
def__init__(self):
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
}
deffetch_and_parse(self, url, selector):
"""通用抓取 + 解析方法"""
try:
resp = requests.get(url, headers=self.headers, timeout=10)
resp.encoding = resp.apparent_encoding # 自动探测编码
soup = BeautifulSoup(resp.text, "lxml")
items = soup.select(selector)
articles = []
for item in items:
link_el = item.select_one("a")
title = link_el.get_text(strip=True) if link_el else""
link = link_el["href"] if link_el and link_el.has_attr("href") else""
articles.append({"title": title, "link": link})
return articles
exceptExceptionas e:
print(f" 抓取失败 ({url}): {e}")
return []
defrun(self, output_file="aggregated_news.csv"):
"""运行聚合器"""
print("开始抓取新闻...\n")
sources = [
# (URL, CSS选择器, 网站名称)
(
"https://news.ycombinator.com/",
".athing td.title",
"Hacker News"
),
]
all_articles = []
for url, selector, name in sources:
print(f" 抓取 {name}...")
articles = self.fetch_and_parse(url, selector)
for article in articles:
article["source"] = name
all_articles.append(article)
print(f" 抓取到 {len(articles)} 条")
time.sleep(random.uniform(2, 4)) # 礼貌地等待
# 保存
if all_articles:
withopen(output_file, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=["title", "link", "source"])
writer.writeheader()
writer.writerows(all_articles)
print(f"\n✅ 共抓取 {len(all_articles)} 条新闻,保存到 {output_file}")
else:
print("\n⚠️ 没有抓取到任何数据,请检查目标网站是否变化")
# 运行
if__name__ == "__main__":
aggregator = NewsAggregator()
aggregator.run()
```
---
## 5.8 练习题
### 练习 1:抓取并统计词频
写一个爬虫,抓取一段文本页面,统计出现频率最高的 10 个词。
**提示**:先用 requests 获取页面,用 BeautifulSoup 提取正文,再用字符串分割统计。
```python
# 参考答案
import requests
from collections import Counter
# 获取一页纯文本内容
url = "https://quotes.toscrape.com"
resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
from bs4 import BeautifulSoup
soup = BeautifulSoup(resp.text, "lxml")
# 提取所有名言文本
texts = [q.find("span", class_="text").get_text() for q in soup.select("div.quote")]
full_text = " ".join(texts).lower()
# 简单的词频统计(去掉常见停用词)
stop_words = {"the", "and", "to", "of", "a", "is", "in", "it", "that", "was", "for", "on", "with", "as", "i", "this"}
words = [w.strip(".,;:\"!?()-") for w in full_text.split() if w.lower() notin stop_words andlen(w) > 2]
counter = Counter(words)
print("Top 10 高频词:")
for word, count in counter.most_common(10):
print(f" {word}: {count} 次")
```
### 练习 2:构建图片下载器
抓取一个图片网站的页面,将所有 <img> 标签的图片下载到本地文件夹。
**提示**:提取 src 属性,用 requests 下载二进制内容,保存到文件。
```python
# 参考答案
import os
import requests
from bs4 import BeautifulSoup
url = "https://quotes.toscrape.com"
resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
soup = BeautifulSoup(resp.text, "lxml")
os.makedirs("images", exist_ok=True)
# 找所有图片
imgs = soup.find_all("img")
print(f"找到 {len(imgs)} 张图片")
for img in imgs:
src = img.get("src")
if src:
# 处理相对路径
if src.startswith("//"):
src = "https:" + src
elif src.startswith("/"):
src = url.rstrip("/") + src
try:
img_resp = requests.get(src, timeout=10)
filename = src.split("/")[-1] or"image.jpg"
filepath = os.path.join("images", filename)
withopen(filepath, "wb") as f:
f.write(img_resp.content)
print(f" 已下载: {filepath}")
exceptExceptionas e:
print(f" 下载失败 {src}: {e}")
```
### 练习 3:分页爬虫
上面的豆瓣 Top 250 只抓取了 25 条。请修改代码,让它抓取全部 10 页(250 条),并把结果保存为 JSON 格式而不是 CSV。
**提示**:循环翻页 + `json.dump`。
```python
# 参考答案要点
import json
all_items = []
for page inrange(10):
url = f"https://movie.douban.com/top250?start={page*25}&filter="
# ... 解析 + 提取 ...
all_items.extend(parsed_items)
withopen("douban_top250.json", "w", encoding="utf-8") as f:
json.dump(all_items, f, ensure_ascii=False, indent=2)
```
### 练习 4:实现一个简单的 API 客户端
用 requests 调用一个公开的免费 API(如 https://jsonplaceholder.typicode.com/posts),获取并展示数据。
```python
# 参考答案
import requests
resp = requests.get("https://jsonplaceholder.typicode.com/posts?_limit=5")
posts = resp.json() # 直接得到 Python 字典
for post in posts:
print(f"[{post['userId']}] {post['title']}")
print(f" {post['body'][:80]}...")
print()
```
### 练习 5:综合实战 —— 天气预报采集器
写一个爬虫,访问一个天气网站(或者直接用公开的天气 API),抓取当前城市的温度、湿度、风力等信息,打印出来。
```python
# 参考思路(使用和风天气免费 API)
import requests
API_KEY = "你的和风天气API Key"# https://dev.qweather.com/ 免费注册获取
city = "beijing"
url = f"https://geoapi.qweather.com/v2/city/key?location={city}"
resp = requests.get(url)
city_key = resp.json()["location"][0]["id"]
weather_url = f"https://devapi.qweather.com/v7/weather/now?location={city_key}&key={API_KEY}"
weather = requests.get(weather_url).json()["now"]
print(f"城市: {city_key}")
print(f"温度: {weather['temp']}°C")
print(f"体感: {weather['feelsLike']}°C")
print(f"湿度: {weather['humidity']}%")
print(f"风向: {weather['windDir']} ({weather['windScale']}级)")
print(f"天气: {weather['text']}")
```
---
## 5.9 本课时知识点小结
| 知识点 | 关键词 |
|--------|--------|
| HTTP 请求 | GET / POST / Headers / Timeout / Session |
| 网页解析 | BeautifulSoup / find / select / CSS 选择器 |
| 数据存储 | CSV / JSON / 文件写入 |
| 反爬应对 | User-Agent / 随机延迟 / 重试机制 / Cookie |
| 动态页面 | Selenium / Playwright |
---
## 5.10 下期预告
下一期(Episode 06),我们要进入**数据分析**的世界!你将学到:
-**NumPy**:数组运算的利器,数据处理的基础
-**Pandas**:Python 数据分析的瑞士军刀,DataFrame 操作、数据清洗、分组聚合
-**Matplotlib**:让你的数据"开口说话",绘制各种精美图表
-**实战**:用真实数据集做一次完整的数据分析项目
准备好你的 Python,我们下期见!🐍📊