Python爬虫第五讲解|全面解析requests库进阶应用与反爬策略
本页面系统梳理Python爬虫第五讲解核心知识体系,聚焦requests库高级特性、会话管理机制、代理池构建逻辑、动态伪装技巧及主流反反爬方案。内容基于真实项目经验提炼,覆盖网民高频搜索的20+技术难点,包含完整可运行代码示例、调试技巧及避坑指南,助您突破静态爬虫瓶颈,迈向动态对抗新阶段。
● requests库底层原理与urllib对比优势
● Session对象状态保持机制与Cookie处理深度解析
● 代理IP池动态构建与健康检查策略
● 请求头伪装技术:User-Agent轮换与Referer伪造
● 常见反爬机制识别与应对方案(JS渲染/参数加密/频率限制)
● 实战项目:高并发新闻采集系统设计思路
● 附赠20+常见问题解答与调试命令集
本讲内容需具备以下基础能力:
- 熟悉Python基础语法与模块导入机制
- 掌握HTTP协议基本概念(GET/POST、状态码、请求头)
- 了解JSON/XML数据结构解析方法
- 具备基础命令行操作能力(Linux/Mac/Windows终端)
- 理解正则表达式基础语法与re模块使用
未掌握上述内容者,建议先学习Python爬虫第一至第四讲,确保知识体系连贯性。
一、requests库核心能力深度解析
1.1 requests与urllib的性能对比
在实际项目测试中,requests库在以下维度显著优于urllib:
| 对比维度 | requests | urllib |
|---|---|---|
| 代码简洁度 | 3-5行完成复杂请求 | 10+行需手动处理细节 |
| 会话管理 | 内置Session支持 | 需自行实现Cookie持久化 |
| 异常处理 | 统一异常体系 | 多种异常类型需分别捕获 |
| 重定向处理 | 自动处理+可配置 | 需手动设置allow_redirects |
| 中文编码 | 自动识别响应编码 | 需手动指定encoding |
1.2 requests核心参数详解
requests.request()方法支持以下关键参数:
- method:HTTP请求方法(GET/POST/PUT/DELETE等)
- url:目标URL地址(支持HTTPS协议自动处理)
- params:URL查询参数(字典形式自动编码)
- data:请求体数据(POST请求时自动编码为application/x-www-form-urlencoded)
- json:JSON格式数据(自动序列化并设置Content-Type)
- headers:自定义请求头(字典结构覆盖默认值)
- cookies:自定义Cookie值(自动处理域/路径/过期时间)
- files:文件上传参数(multipart/form-data编码)
- timeout:请求超时时间(秒,支持元组形式分隔连接/读取超时)
- allow_redirects:是否允许重定向(默认True)
- proxies:代理配置字典
- verify:SSL证书验证开关(默认True)
- cert:客户端证书路径(用于双向认证)
1.3 响应对象深度解析
requests.Response对象提供以下核心属性:
- status_code:HTTP状态码(200/404/503等)
- headers:响应头字典(支持大小写不敏感访问)
- cookies:响应设置的Cookie集合
- text:文本形式响应体(自动根据charset解码)
- content:二进制形式响应体(用于图片/文件下载)
- json():JSON响应体解析方法(自动检测Content-Type)
- encoding:响应编码声明(可手动修改)
- url:最终请求URL(含重定向后的地址)
- history:重定向历史记录列表
import requests
url = "https://httpbin.org/get"
params = {"q": "python爬虫", "page": 2}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"Accept": "application/json"
}
response = requests.get(url, params=params, headers=headers)
print("状态码:", response.status_code)
print("响应头:", response.headers)
print("编码声明:", response.encoding)
print("最终URL:", response.url)
print("是否重定向:", bool(response.history))
print("JSON数据:", response.json())
print("原始响应体:", response.text[:200])
1.4 超时处理与异常捕获
requests库提供两种超时机制:
- 单值超时:timeout=5 表示连接+读取总超时5秒
- 元组超时:timeout=(3, 7) 表示连接超时3秒,读取超时7秒
常见异常类型及处理方式:
| 异常类型 | 触发条件 | 处理建议 |
|---|---|---|
| requests.exceptions.Timeout | 请求超时 | 重试机制+延迟增加 |
| requests.exceptions.ConnectionError | 网络连接失败 | 检查网络/代理/目标服务 |
| requests.exceptions.HTTPError | 非2xx状态码 | 根据状态码分类处理 |
| requests.exceptions.TooManyRedirects | 重定向超过限制 | 检查重定向循环 |
| requests.exceptions.RequestException | 所有requests异常基类 | 兜底异常捕获 |
import requests
def safe_request(method, url, **kwargs):
try:
timeout = kwargs.pop("timeout", (3, 7))
response = requests.request(method, url, timeout=timeout, **kwargs)
response.raise_for_status()
return response
except requests.exceptions.Timeout:
print("请求超时,请检查网络连接或增加超时时间")
return None
except requests.exceptions.ConnectionError:
print("连接失败,请确认目标服务器状态")
return None
except requests.exceptions.HTTPError as e:
print(f"HTTP错误:{e.response.status_code}")
return None
except requests.exceptions.RequestException as e:
print(f"未知请求异常:{e}")
return None
# 使用示例
res = safe_request("GET", "https://httpbin.org/status/404")
if res:
print("请求成功")
二、会话管理与Cookie处理
2.1 Session对象工作原理
Python爬虫第五讲解重点强调:Session对象通过维护以下状态实现会话保持:
- 自动处理Cookie传递(自动添加Set-Cookie中的键值对)
- 保持连接复用(底层使用urllib3连接池)
- 统一请求参数(可设置默认headers/cookies/proxies)
- 状态持久化(支持pickle序列化Session对象)
import requests
session = requests.Session()
# 第一次请求获取Cookie
r1 = session.get("https://httpbin.org/cookies/set?name=python爬虫")
print("首次响应Cookie:", session.cookies.get_dict())
# 第二次请求自动携带Cookie
r2 = session.get("https://httpbin.org/cookies")
print("自动携带Cookie:", r2.json())
# 输出结果:
# 首次响应Cookie: {'name': 'python爬虫'}
# 自动携带Cookie: {'cookies': {'name': 'python爬虫'}}
2.2 Cookie持久化与跨会话复用
在需要长期维持登录状态的场景中,可将Session对象序列化:
import requests
import pickle
import os
def save_session(session, filename):
with open(filename, 'wb') as f:
pickle.dump(session, f)
def load_session(filename):
if os.path.exists(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
return requests.Session()
# 使用示例
session = load_session("mysession.pkl")
# 执行需要登录的操作...
save_session(session, "mysession.pkl")
2.3 自定义Cookie策略
Session支持三种Cookie注入方式:
- 请求时临时传入cookies参数
- 通过session.cookies.set()设置持久Cookie
- 从浏览器导出Cookie后批量导入
2.4 会话状态调试技巧
调试会话问题时,可使用以下命令:
# 查看当前会话所有Cookie
print(session.cookies)
# 查看特定域的Cookie
print(session.cookies.get_dict(domain="example.com"))
# 手动设置Cookie
session.cookies.set("token", "abc123", domain="example.com", path="/")
# 清除特定Cookie
session.cookies.clear(domain="example.com", path="/")
# 清除所有Cookie
session.cookies.clear()
三、代理IP池构建与管理
3.1 代理工作原理
代理IP在Python爬虫第五讲解中被定义为请求中转站,其核心价值在于:
- 隐藏真实IP地址(防止目标网站封禁)
- 绕过IP频率限制(轮换不同IP突破访问限制)
- 模拟多地域用户(获取地区差异内容)
- 突破地区封禁(访问地理限制内容)
3.2 代理类型对比
| 代理类型 | 工作原理 | 适用场景 | 风险等级 |
|---|---|---|---|
| 透明代理 | 传递真实IP+代理IP | 测试环境 | 高 |
| 匿名代理 | 隐藏真实IP+显示代理IP | 常规爬取 | 中 |
| 高匿代理 | 完全隐藏真实IP | 生产环境 | 低 |
| SOCKS代理 | 传输层代理(支持TCP/UDP) | 特殊协议需求 | 中 |
3.3 代理IP池构建流程
标准IP池构建包含以下步骤:
- 爬取免费代理网站(需添加反爬策略)
- 验证代理可用性(测试连接目标网站)
- 健康检查(定期检测存活状态)
- 失效移除(自动剔除异常IP)
- 动态补充(定时抓取新IP)
import requests
from concurrent.futures import ThreadPoolExecutor
def validate_proxy(proxy, timeout=5):
test_url = "https://httpbin.org/ip"
try:
proxies = {"http": proxy, "https": proxy}
response = requests.get(test_url, proxies=proxies, timeout=timeout)
if response.status_code == 200:
return {"ip": proxy, "valid": True}
except:
pass
return {"ip": proxy, "valid": False}
# 使用线程池并发验证
proxies = ["http://123.123.123.123:8080", "http://111.111.111.111:8080"]
with ThreadPoolExecutor(max_workers=10) as executor:
results = list(executor.map(validate_proxy, proxies))
valid_proxies = [r["ip"] for r in results if r["valid"]]
print(f"有效代理数量:{len(valid_proxies)}")
3.4 动态代理池实现方案
推荐使用以下数据结构管理代理池:
class ProxyPool:
def __init__(self):
self.proxies = [] # 待用代理列表
self.used = [] # 已使用代理列表
self.blacklist = [] # 黑名单IP
def add_proxy(self, proxy):
if proxy not in self.blacklist and proxy not in self.proxies:
self.proxies.append(proxy)
def get_proxy(self):
if not self.proxies:
return None
proxy = self.proxies.pop(0)
self.used.append(proxy)
return proxy
def mark_invalid(self, proxy):
if proxy in self.proxies:
self.proxies.remove(proxy)
if proxy in self.used:
self.used.remove(proxy)
if proxy not in self.blacklist:
self.blacklist.append(proxy)
def refresh(self):
# 定时补充新代理
new_proxies = self._fetch_new_proxies()
for p in new_proxies:
self.add_proxy(p)
def request_with_proxy(session, method, url, pool, **kwargs):
proxy = pool.get_proxy()
if not proxy:
raise Exception("代理池为空")
try:
response = session.request(method, url,
proxies={"http": proxy, "https": proxy},
**kwargs)
return response
except Exception as e:
pool.mark_invalid(proxy)
raise e
四、主流反爬机制应对策略
4.1 请求头伪装技术
Python爬虫第五讲解特别强调:请求头伪装是基础但关键环节,需同时处理以下要素:
- User-Agent轮换(模拟不同浏览器/设备)
- Accept-Language设置(匹配地域偏好)
- Referer伪造(模拟来源页面)
- Accept-Encoding处理(gzip/deflate解压)
- Connection保持(keep-alive优化性能)
import random
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15",
"Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0"
]
def get_headers(url):
return {
"User-Agent": random.choice(USER_AGENTS),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Referer": "https://www.google.com/",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1"
}
4.2 常见反爬机制识别
通过以下特征可识别目标网站反爬策略:
| 反爬特征 | 识别方法 | 应对方案 |
|---|---|---|
| 403 Forbidden | 请求被服务器拒绝 | 检查请求头/代理/频率 |
| 空白响应 | 返回空内容或重定向 | 检查JS渲染/参数加密 |
| 验证码弹窗 | 返回包含验证码的HTML | OCR识别/人工打码/绕过登录 |
| 异常数据 | JSON含异常字段(如"code":500) | 分析加密参数生成逻辑 |
| IP封锁 | 固定IP连续请求失败 | 切换代理IP池 |
4.3 参数加密应对策略
针对常见参数加密场景(如sign/timestamp/token),推荐以下解决路径:
- 分析请求参数生成逻辑(观察请求URL变化)
- 定位JS加密函数(浏览器开发者工具Network面板)
- 逆向加密算法(提取关键函数逻辑)
- Python重写加密逻辑(或使用PyExecJS执行JS)
import execjs
# 假设目标网站加密函数
js_code = """
function get_sign(token, timestamp) {
return CryptoJS.MD5(token + timestamp).toString();
}
"""
ctx = execjs.compile(js_code)
sign = ctx.call("get_sign", "abc123", "1672531200")
print("加密结果:", sign)
4.4 动态渲染页面应对
当目标网站使用JS动态加载内容时,可采用以下方案:
- Selenium自动化(模拟真实浏览器行为)
- Pyppeteer无头浏览器(Chromium内核)
- 分析XHR请求(直接获取JSON数据)
- 使用Playwright(微软开源方案)
推荐优先分析XHR请求,因其数据结构清晰、响应速度快、无需浏览器环境。
五、综合实战项目拆解
5.1 新闻采集系统设计
本项目实现以下功能模块:
- 多源新闻抓取(支持不同网站结构适配)
- 内容去重(基于内容指纹算法)
- 存储管理(支持MySQL/Elasticsearch)
- 定时任务(基于APScheduler)
- 监控告警(异常情况邮件通知)
from datetime import datetime
import hashlib
class NewsCrawler:
def __init__(self):
self.session = requests.Session()
self.proxies = self._init_proxy_pool()
self.cache = {}
def _init_proxy_pool(self):
pool = ProxyPool()
pool.refresh()
return pool
def _gen_fingerprint(self, content):
return hashlib.md5(content.encode()).hexdigest()[:16]
def fetch_news(self, source_config):
url = source_config["url"]
headers = get_headers(url)
response = request_with_proxy(
self.session, "GET", url,
self.proxies, headers=headers
)
if not response:
return []
# 解析新闻列表
items = self._parse_list(response.text, source_config)
# 去重处理
unique_items = []
for item in items:
fp = self._gen_fingerprint(item["content"])
if fp not in self.cache:
self.cache[fp] = True
unique_items.append(item)
return unique_items
def _parse_list(self, html, config):
# 根据不同网站配置解析
# 实际项目中使用lxml/xpath进行精准提取
pass
5.2 数据存储方案
推荐采用分层存储策略:
- 原始数据存档(JSON格式,便于后续分析)
- 结构化数据入库(MySQL/Elasticsearch)
- 缓存高频数据(Redis加速查询)
import mysql.connector
class NewsDB:
def __init__(self):
self.conn = mysql.connector.connect(
host="localhost",
user="crawler",
password="***",
database="news_db"
)
self.cursor = self.conn.cursor()
def save_news(self, news_item):
sql = """
INSERT INTO news (title, content, source, publish_time, url)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
title=VALUES(title),
content=VALUES(content)
"""
self.cursor.execute(sql, (
news_item["title"],
news_item["content"],
news_item["source"],
news_item["publish_time"],
news_item["url"]
))
self.conn.commit()
六、高频问题答疑专区
Q1:requests库和urllib到底该选哪个?
A:在Python爬虫第五讲解中,我们强烈推荐requests库,因其具备以下优势:
- API设计更符合人类思维(参数直观易懂)
- 自动处理编码和gzip压缩
- 内置会话管理机制
- 异常处理更统一
- 社区支持更活跃(大量实战案例)
仅在以下场景考虑urllib:
- 无法安装第三方库的受限环境
- 需要极细粒度控制HTTP细节
- 学习HTTP协议底层原理
Q2:代理IP池如何保证可用性?
A:我们采用三层验证机制:
- 预验证:抓取后立即测试可用性
- 运行时监控:每次请求前验证代理
- 定期健康检查:后台定时扫描存活IP
同时建立IP质量评分体系,优先使用高分代理。
Q3:遇到验证码怎么办?
A:根据验证码复杂度选择方案:
- 简单图片验证码:使用Tesseract OCR识别
- 滑动验证码:模拟人类滑动轨迹
- 点选验证码:接入打码平台(如云打码)
- 极验验证码:分析其JS加密逻辑绕过
注意:高风险网站(如银行/支付平台)应避免绕过验证码,遵守robots.txt规定。
Q4:参数加密如何逆向?
A:推荐逆向步骤:
- 定位加密参数(观察URL中sign/timestamp等字段)
- 搜索JS源码(F12开发者工具→Sources面板)
- 设置断点调试(观察参数生成过程)
- 提取关键函数(提取加密逻辑)
- Python重写(或使用PyExecJS)
关键技巧:使用Chrome DevTools的"Blackbox Script"功能排除无关代码干扰。
● Python爬虫第五讲解配套代码库:github.com/xservx/crawler5
● 免费代理IP监控平台:ip8.com
● 请求头生成工具:httpbin.org
● 在线JS混淆工具:obfuscator.io
● 网站robots.txt检查:technicalseo.com