⚡requests 模块核心价值解析
requests 是Python中最流行的HTTP客户端库,由Kenneth Reitz开发并维护,以简洁优雅的API设计著称。它构建于urllib3之上,屏蔽了底层socket编程的复杂性,为开发者提供了一套高度抽象但功能完备的网络请求接口。
相较于Python内置的urllib库,requests 具有以下显著优势:
支持完整的HTTP/1.1标准特性(包括keep-alive、chunked编码、multipart编码等)
自动处理gzip/deflate压缩响应
原生支持HTTPS证书验证(基于certifi提供的CA证书库)
内置连接池管理,显著提升并发请求性能
提供Session对象实现Cookie持久化与连接复用
异常处理机制清晰明确,错误信息直观易读
在实际爬虫开发中,requests 模块已成为事实标准。无论是简单的GET请求还是复杂的POST表单提交,无论是需要处理动态参数的登录流程,还是涉及OAuth认证的API调用,requests 都能提供简洁可靠的解决方案。其设计理念体现了“优雅胜于粗暴”(Elegance over brute force)的哲学,让开发者专注于业务逻辑而非底层细节。
特别值得注意的是,requests 的API设计严格遵循RESTful规范,方法命名与HTTP动词一一对应(get/post/put/delete/head/options),极大降低了学习成本。同时,其参数传递方式高度灵活:查询参数可作为字典传入params参数,表单数据可作为data或json参数传递,请求头可通过headers参数自定义, cookies可通过cookies参数注入——这种设计让复杂请求的构造变得直观而安全。
在反爬机制日益复杂的今天,requests 模块通过丰富的配置项为开发者提供了强大的应对能力:通过自定义User-Agent模拟不同设备,通过设置Referer规避来源校验,通过Cookie池管理实现账号轮换,通过代理IP池突破频率限制。这些能力的实现都建立在对requests 核心机制的深入理解之上,而本文将系统讲解这些关键技术点。
⚙️ 安装与环境配置
安装requests 模块非常简单,推荐使用pip工具进行安装。在终端中执行以下命令即可完成安装:
pip install requests
安装完成后,可通过Python交互式解释器验证安装是否成功:
>>> import requests
>>> requests.__version__
'2.31.0'
当前最新稳定版本为2.31.0(2024年6月更新),该版本修复了若干安全漏洞并优化了性能表现。建议定期关注获取最新版本信息。
在某些特殊场景下(如企业内网环境),可能需要指定镜像源安装。例如使用阿里云镜像源:
pip install -i https://mirrors.aliyun.com/pypi/simple/ requests
安装过程中可能遇到网络超时问题,可通过增加超时参数解决:
pip install --default-timeout=100 requests
为确保爬虫程序的稳定性,强烈建议在虚拟环境中安装依赖。使用python -m venv创建虚拟环境后,激活环境再执行安装命令,可避免不同项目间的依赖冲突问题。
值得注意的是,requests 模块依赖于certifi提供的证书库进行HTTPS请求验证。certifi是Python生态系统中广泛使用的证书包,包含Mozilla维护的CA证书列表。安装requests 时会自动安装certifi,无需额外操作。
在某些特殊网络环境(如企业代理服务器)中,可能需要配置SSL证书路径。可通过设置REQUESTS_CA_BUNDLE环境变量指定自定义证书路径:
export REQUESTS_CA_BUNDLE=/path/to/custom/cacert.pem
对于Windows系统,可在命令提示符中执行:
set REQUESTS_CA_BUNDLE=C:\path\to\custom\cacert.pem
这种配置方式特别适用于需要验证自签名证书的内部系统爬取场景。
〔基础请求流程〕
requests 模块的使用遵循统一的请求构造模式:首先创建请求参数字典,然后调用对应方法发送请求,最后处理返回的Response对象。整个流程清晰直观,符合HTTP协议的基本逻辑。
最简单的GET请求示例如下:
import requests
url = 'https://httpbin.org/get'
response = requests.get(url)
print(response.status_code) # 200
print(response.text) # 响应内容
该代码执行后,requests.get()方法会构造一个HTTP GET请求,向指定URL发送请求并返回Response对象。Response对象包含status_code(状态码)、text(响应文本)、headers(响应头)等关键属性。
POST请求的构造方式类似,但需要指定data参数传递表单数据:
import requests
url = 'https://httpbin.org/post'
data = {'username': 'testuser', 'password': 'secret123'}
response = requests.post(url, data=data)
print(response.json()) # 以JSON格式解析响应
当请求数据为JSON格式时,推荐使用json参数而非data参数,这样requests 会自动设置Content-Type为application/json:
import requests
url = 'https://httpbin.org/post'
payload = {'key': 'value', 'list': [1, 2, 3]}
response = requests.post(url, json=payload)
print(response.json())
Response对象的text属性返回解码后的字符串内容,但其解码方式依赖于响应头中的charset信息。当服务器未正确声明编码时,可能出现乱码问题。此时可通过response.encoding手动指定编码:
response.encoding = 'utf-8' # 显式指定编码
print(response.text)
对于二进制响应(如图片、PDF文件),应使用content属性获取字节流:
response = requests.get('https://httpbin.org/image/png')
with open('image.png', 'wb') as f:
f.write(response.content)
Response对象还提供json()方法,可直接将响应体解析为Python字典。但需要注意:只有当响应头Content-Type为application/json或application/vnd.api+json时,该方法才可靠工作。对于其他情况,建议先检查响应内容再调用json():
try:
data = response.json()
except ValueError:
print('响应不是有效的JSON格式')
在实际爬虫开发中,建议始终对响应进行状态码检查。可使用response.raise_for_status()方法在非2xx状态码时抛出HTTPError异常:
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(f'HTTP错误: {e}')
这种异常处理机制让错误定位更加精准,避免了因静默失败导致的调试困难。
〈参数传递技巧〉
requests 模块支持多种参数传递方式,每种方式适用于不同场景。理解这些差异对构建可靠爬虫至关重要。
查询参数(Query Parameters)通常通过params参数传递,支持字典、元组列表和字符串等多种格式:
import requests
url = 'https://httpbin.org/get'
params = {'q': 'python爬虫', 'page': 2}
response = requests.get(url, params=params)
print(response.url) # https://httpbin.org/get?q=python%E7%88%AC%E8%99%AB&page=2
params参数会自动进行URL编码,将中文字符转换为UTF-8百分号编码格式。这种编码方式符合RFC 3986标准,确保特殊字符(如&、=、?)不会破坏URL结构。
当需要传递重复参数时,可使用元组列表格式:
params = [('key1', 'value1'), ('key1', 'value2')]
response = requests.get(url, params=params)
print(response.url) # 包含两个key1参数
表单数据(Form Data)可通过data参数传递,适用于application/x-www-form-urlencoded格式:
data = {'username': 'test', 'password': '123456'}
response = requests.post(url, data=data)
当data参数为字符串时,需手动设置Content-Type头:
data = 'raw=string&data=here'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(url, data=data, headers=headers)
JSON数据推荐使用json参数,它会自动设置正确的Content-Type头并序列化数据:
payload = {'name': '张三', 'age': 28, 'hobbies': ['编程', '阅读']}
response = requests.post(url, json=payload)
文件上传通过files参数实现,支持单文件和多文件上传:
files = {'file': open('document.pdf', 'rb')}
response = requests.post(url, files=files)
为文件指定自定义文件名和MIME类型:
files = {
'file': ('report.pdf', open('report.pdf', 'rb'), 'application/pdf')
}
response = requests.post(url, files=files)
当上传大文件时,建议使用流式上传避免内存溢出:
def file_generator():
with open('large_file.dat', 'rb') as f:
while chunk := f.read(8192):
yield chunk
files = {'file': ('large_file.dat', file_generator())}
response = requests.post(url, files=files)
这种生成器模式确保文件以固定大小的块传输,显著降低内存占用。
【会话管理机制】
Session对象是requests 模块实现状态保持的核心。它模拟浏览器行为,自动管理Cookie、连接池和请求头,特别适用于需要登录验证的网站爬取。
创建Session对象并使用:
import requests
session = requests.Session()
session.headers.update({'User-Agent': 'Custom UA'})
# 自动携带之前请求设置的Cookie
response1 = session.get('https://httpbin.org/cookies/set?name=value')
response2 = session.get('https://httpbin.org/cookies')
print(response2.json()) # {'cookies': {'name': 'value'}}
Session对象自动继承初始设置,包括headers、auth、proxies等配置。这避免了在每次请求中重复传递相同参数。
会话管理的典型应用场景是登录流程模拟:
session = requests.Session()
# 1. 获取登录页面以获取CSRF令牌
login_page = session.get('https://example.com/login')
csrf_token = extract_csrf_token(login_page.text) # 假设已实现提取逻辑
# 2. 提交登录表单
login_data = {
'username': 'user',
'password': 'pass',
'csrf_token': csrf_token
}
login_response = session.post('https://example.com/login', data=login_data)
# 3. 访问需要登录的页面
profile = session.get('https://example.com/profile')
print(profile.text) # 包含登录后内容
Session对象通过CookieJar管理Cookie,可导出为Mozilla格式供浏览器使用:
import http.cookiejar
# 导出Cookie
session.cookies.save('cookies.txt', ignore_discard=True, ignore_expires=True)
# 导入Cookie
session.cookies = http.cookiejar.LWPCookieJar('cookies.txt')
session.cookies.load(ignore_discard=True, ignore_expires=True)
对于需要持久化Cookie的场景,建议使用MozillaCookieJar格式:
session.cookies = http.cookiejar.MozillaCookieJar('cookies.txt')
session.cookies.load(ignore_discard=True, ignore_expires=True)
Session还支持上下文管理器语法,确保资源正确释放:
with requests.Session() as session:
session.headers.update({'User-Agent': 'Mozilla/5.0'})
response = session.get('https://httpbin.org/headers')
print(response.json())
这种写法在异常发生时自动关闭连接,避免资源泄漏。
[代理IP池配置]
代理IP池是突破网站频率限制和IP封禁的核心技术。requests 通过proxies参数支持HTTP/HTTPS/SOCKS代理。
HTTP代理配置示例:
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080'
}
response = requests.get('https://httpbin.org/ip', proxies=proxies)
print(response.json())
带认证的代理配置:
proxies = {
'http': 'http://user:password@10.10.1.10:3128',
'https': 'http://user:password@10.10.1.10:1080'
}
SOCKS代理需要额外安装依赖:
pip install 'requests[socks]'
proxies = {
'http': 'socks5://10.10.1.10:1080',
'https': 'socks5://10.10.1.10:1080'
}
构建动态代理池的推荐方案:
import random
def get_random_proxy():
proxy_pool = [
'http://user:pass@10.10.1.10:3128',
'http://user:pass@10.10.1.11:3128',
'http://user:pass@10.10.1.12:3128'
]
return random.choice(proxy_pool)
proxies = {
'http': get_random_proxy(),
'https': get_random_proxy()
}
response = requests.get('https://httpbin.org/ip', proxies=proxies)
对于需要验证代理有效性的场景,建议先进行健康检查:
def validate_proxy(proxy):
try:
response = requests.get(
'https://httpbin.org/ip',
proxies={'http': proxy, 'https': proxy},
timeout=5
)
return response.status_code == 200
except requests.exceptions.RequestException:
return False
# 过滤有效代理
valid_proxies = [p for p in proxy_pool if validate_proxy(p)]
Session对象可统一管理代理设置:
session = requests.Session()
session.proxies.update({
'http': get_random_proxy(),
'https': get_random_proxy()
})
# 所有请求自动使用代理
response = session.get('https://httpbin.org/ip')
在生产环境中,建议结合代理IP管理服务(如快代理、芝麻HTTP)实现自动代理轮换。通过API获取代理列表后,可实现智能故障转移和健康监控。
※异常处理体系
requests 模块定义了完整的异常层次结构,所有异常均继承自RequestException。合理使用异常处理可提升爬虫稳定性。
主要异常类型及触发条件:
异常类型
触发条件
常见场景
RequestException
所有请求异常的基类
通用异常捕获
HTTPError
HTTP状态码错误(4xx/5xx)
调用raise_for_status()时
ConnectionError
网络连接失败
DNS解析失败、连接超时等
Timeout
请求超时
设置timeout参数且超时
TooManyRedirects
重定向次数过多
超过max_redirects限制
SSLError
SSL证书验证失败
证书过期、域名不匹配等
ProxyError
代理连接失败
代理服务器不可用
完整的异常处理模板:
import requests
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
except requests.exceptions.Timeout:
print('请求超时,建议重试')
except requests.exceptions.TooManyRedirects:
print('重定向次数过多,请检查URL')
except requests.exceptions.HTTPError as e:
print(f'HTTP错误: {e.response.status_code} - {e.response.reason}')
except requests.exceptions.ConnectionError as e:
print(f'连接错误: {e}')
except requests.exceptions.RequestException as e:
print(f'未知错误: {e}')
对于需要自动重试的场景,建议结合retrying库实现:
from retrying import retry
@retry(stop_max_attempt_number=3, wait_fixed=2000)
def fetch_with_retry(url):
response = requests.get(url, timeout=10)
response.raise_for_status()
return response
该装饰器在请求失败时自动重试最多3次,每次间隔2秒。还可添加等待策略(如指数退避):
@retry(stop_max_attempt_number=5,
wait_exponential_multiplier=1000,
wait_exponential_max=10000)
def fetch_with_backoff(url):
response = requests.get(url, timeout=10)
response.raise_for_status()
return response
指数退避策略可显著降低对目标服务器的压力,避免触发更严格的频率限制。
♀Cookie处理技巧
Cookie是会话状态管理的关键,requests 通过cookies参数和Session对象提供灵活的Cookie操作。
直接传递Cookie到单个请求:
cookies = {'session_id': 'abc123', 'user_pref': 'dark_mode'}
response = requests.get(url, cookies=cookies)
使用CookieJar管理复杂Cookie:
import http.cookiejar
cj = http.cookiejar.CookieJar()
# 添加Cookie
ck = http.cookiejar.Cookie(
version=0, name='session', value='12345',
port=None, port_specified=False,
domain='example.com', domain_specified=True, domain_initial_dot=False,
path='/', path_specified=True,
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={}
)
cj.set_cookie(ck)
response = requests.get(url, cookies=cj)
从浏览器导出Cookie的实用技巧:
使用Chrome扩展程序"EditThisCookie"导出JSON格式Cookie
通过浏览器开发者工具Application标签复制Cookie字符串
使用selenium+requests同步Cookie(需先用selenium登录)
解析Cookie字符串为字典:
cookie_str = 'session=abc123; user_id=456; path=/; domain=.example.com'
cookies = {}
for item in cookie_str.split(';'):
if '=' in item:
key, value = item.split('=', 1)
cookies[key.strip()] = value.strip()
在Session中清除特定Cookie:
session = requests.Session()
session.cookies.clear(domain='example.com', path='/')
# 或清除所有Cookie
session.cookies.clear()
设置Cookie过期时间:
import time
# 设置Cookie在1小时后过期
expires = int(time.time()) + 3600
session.cookies.set('session_id', 'abc123', expires=expires)
对于需要自动刷新Cookie的场景,建议实现Cookie刷新机制:
def ensure_valid_cookie(session, refresh_func):
# 检查关键Cookie是否存在且未过期
if not session.cookies.get('session_id'):
refresh_func(session)
该模式特别适用于需要定期登录刷新的网站爬虫。
▲超时控制策略
超时设置是爬虫稳定性的第一道防线。未设置超时的请求可能无限期挂起,导致资源耗尽。
超时参数支持两种格式:
# 连接超时5秒,读取超时10秒
response = requests.get(url, timeout=(5, 10))
# 总超时15秒(连接+读取)
response = requests.get(url, timeout=15)
建议始终使用元组形式设置独立连接和读取超时,因为网络连接和数据传输的延迟特性不同。
超时异常处理最佳实践:
import time
def fetch_with_backoff(url, max_retries=5):
for attempt in range(max_retries):
try:
response = requests.get(url, timeout=(5, 15))
response.raise_for_status()
return response
except requests.exceptions.Timeout:
if attempt == max_retries - 1:
raise
# 指数退避等待
time.sleep(2 ** attempt)
except requests.exceptions.RequestException:
raise
该函数实现指数退避重试:第1次失败等待1秒,第2次等待2秒,第3次等待4秒,依此类推。这种策略在保证重试效率的同时避免对服务器造成压力。
对于需要全局超时设置的场景,可自定义Session子类:
class TimeoutSession(requests.Session):
def __init__(self, timeout=(5, 15)):
super().__init__()
self.timeout = timeout
def request(self, method, url, **kwargs):
kwargs.setdefault('timeout', self.timeout)
return super().request(method, url, **kwargs)
session = TimeoutSession()
response = session.get(url) # 自动使用默认超时
这种设计让超时配置集中管理,避免在每个请求中重复设置。
↖重定向处理机制
默认情况下,requests 会自动跟随3xx重定向。对于需要控制重定向行为的场景,可通过allow_redirects参数禁用。
禁用自动重定向:
response = requests.get(url, allow_redirects=False)
print(response.status_code) # 302
print(response.headers['Location']) # 重定向目标URL
限制最大重定向次数:
response = requests.get(url, max_redirects=3)
自定义重定向处理逻辑:
def follow_redirects(session, url, max_depth=5):
visited = set()
def _follow(current_url, depth):
if depth > max_depth or current_url in visited:
return None
visited.add(current_url)
response = session.get(current_url, allow_redirects=False)
if response.is_redirect:
location = response.headers.get('Location')
if location:
return _follow(session.urljoin(location), depth + 1)
return response
return _follow(url, 0)
该函数可安全处理循环重定向,并记录访问路径用于调试。
重定向安全检查建议:
验证重定向目标是否在允许域名列表内
检查Location头是否包含可疑参数
记录重定向链用于分析反爬策略
对于需要拦截重定向的场景,可结合自定义Adapter实现:
class NoRedirect(requests.adapters.HTTPAdapter):
def send(self, request, **kwargs):
kwargs['allow_redirects'] = False
return super().send(request, **kwargs)
session = requests.Session()
session.mount('http://', NoRedirect())
session.mount('https://', NoRedirect())
这种配置让Session完全禁用自动重定向,所有3xx响应由开发者显式处理。
♀SSL证书验证
HTTPS请求的SSL证书验证是安全通信的基础。默认情况下,requests 会验证服务器证书,但可通过verify参数控制。
禁用SSL验证(⚠️仅用于开发环境):
response = requests.get(url, verify=False)
指定自定义CA证书路径:
response = requests.get(url, verify='/path/to/ca-bundle.crt')
忽略证书验证时会触发警告,可通过以下方式抑制:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
response = requests.get(url, verify=False)
证书验证失败的常见原因:
证书过期
域名不匹配
自签名证书未被信任
中间证书缺失
调试证书问题的实用技巧:
import ssl
import socket
def check_ssl_certificate(hostname, port=443):
context = ssl.create_default_context()
with socket.create_connection((hostname, port)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
cert = ssock.getpeercert()
print('证书主题:', cert['subject'])
print('证书颁发者:', cert['issuer'])
print('过期时间:', cert['notAfter'])
check_ssl_certificate('example.com')
该函数可检查目标网站的证书详细信息,帮助诊断验证失败原因。
对于需要处理自签名证书的场景,建议实现证书固定(Certificate Pinning):
import hashlib
def verify_certificate_fingerprint(response, expected_fp):
cert = response.raw.connection.sock.getpeercert(binary_form=True)
fingerprint = hashlib.sha256(cert).hexdigest()
return fingerprint == expected_fp
# 使用示例
response = requests.get(url, verify=True)
if not verify_certificate_fingerprint(response, 'expected_fingerprint'):
raise Exception('证书指纹不匹配')
证书固定可有效防止中间人攻击,特别适用于金融类网站爬取。
♀流式传输处理
流式传输允许边下载边处理数据,避免大文件占用过多内存。通过stream=True参数启用流式模式。
基本流式下载示例:
with requests.get(url, stream=True) as response:
response.raise_for_status()
with open('large_file.zip', 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk: # 过滤keep-alive块
f.write(chunk)
iter_content()方法按指定大小返回字节块,chunk_size参数可优化I/O性能。推荐值为8192(8KB)的倍数。
流式处理文本数据:
with requests.get(url, stream=True) as response:
response.raise_for_status()
for line in response.iter_lines(decode_unicode=True):
if line:
process_line(line)
iter_lines()方法按行返回内容,decode_unicode=True确保正确处理编码。
进度条显示实现:
import sys
from tqdm import tqdm
def download_with_progress(url, filename):
with requests.get(url, stream=True) as response:
response.raise_for_status()
total = int(response.headers.get('content-length', 0))
with open(filename, 'wb') as f, tqdm(
total=total,
unit='B',
unit_scale=True,
unit_divisor=1024,
desc=filename
) as bar:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
bar.update(len(chunk))
该实现使用tqdm库显示实时下载进度,提升用户体验。
流式上传大文件:
def upload_stream(url, filepath):
def file_stream():
with open(filepath, 'rb') as f:
while chunk := f.read(8192):
yield chunk
response = requests.post(
url,
data=file_stream(),
headers={'Content-Type': 'application/octet-stream'}
)
return response
这种生成器模式确保大文件以固定大小块传输,避免内存溢出。
♂认证机制实现
requests 内置支持多种HTTP认证方式,包括Basic Auth、Digest Auth和OAuth。
基本认证(Basic Auth):
from requests.auth import HTTPBasicAuth
response = requests.get(url, auth=HTTPBasicAuth('user', 'pass'))
简写形式:
response = requests.get(url, auth=('user', 'pass'))
摘要认证(Digest Auth):
from requests.auth import HTTPDigestAuth
response = requests.get(url, auth=HTTPDigestAuth('user', 'pass'))
OAuth 1.0a认证(需额外安装oauth1):
pip install requests-oauthlib
from requests_oauthlib import OAuth1
oauth = OAuth1(
client_key='your_consumer_key',
client_secret='your_consumer_secret',
resource_owner_key='your_access_token',
resource_owner_secret='your_access_token_secret'
)
response = requests.get(url, auth=oauth)
OAuth 2.0认证(推荐使用requests-oauthlib):
from requests_oauthlib import OAuth2Session
client_id = 'your_client_id'
client_secret = 'your_client_secret'
authorization_base_url = 'https://provider.com/oauth/authorize'
token_url = 'https://provider.com/oauth/token'
oauth = OAuth2Session(client_id, redirect_uri='https://example.com/callback')
authorization_url, state = oauth.authorization_url(authorization_base_url)
# 获取访问令牌
token = oauth.fetch_token(
token_url,
client_secret=client_secret,
authorization_response='https://example.com/callback?code=...'
)
response = oauth.get(url)
自定义认证类实现:
class TokenAuth(requests.auth.AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers['Authorization'] = f'Bearer {self.token}'
return r
response = requests.get(url, auth=TokenAuth('your_token'))
这种实现方式适用于API Key、JWT等自定义认证机制。
♀调试技巧集合
调试是爬虫开发的关键环节。requests 模块提供多种调试手段帮助定位问题。
启用详细日志记录:
import logging
import http.client as http_client
http_client.HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger("urllib3").setLevel(logging.DEBUG)
response = requests.get(url)
该配置会输出完整的HTTP请求/响应报文,包括请求头、响应头和内容。
打印请求URL(含参数):
from requests import Request, Session
s = Session()
req = Request('GET', url, params={'q': 'test'})
prepped = s.prepare_request(req)
print(prepped.url) # 完整URL(含编码参数)
检查响应内容编码:
response = requests.get(url)
print(response.encoding) # 检测到的编码
print(response.apparent_encoding) # chardet检测的编码
使用chardet进行编码检测:
import chardet
raw_data = response.content
detected = chardet.detect(raw_data)
print(detected) # {'encoding': 'utf-8', 'confidence': 0.99}
保存请求和响应数据用于分析:
import json
from datetime import datetime
def save_request_info(response, filepath='request_log.json'):
log = {
'timestamp': datetime.now().isoformat(),
'request': {
'url': response.request.url,
'method': response.request.method,
'headers': dict(response.request.headers)
},
'response': {
'status_code': response.status_code,
'headers': dict(response.headers),
'elapsed': response.elapsed.total_seconds()
}
}
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(log, f, indent=2, ensure_ascii=False)
该函数可生成完整的请求分析报告,便于后续调试。
♀最佳实践总结
结合多年爬虫开发经验,总结requests 模块使用最佳实践:
始终设置超时
使用Session管理会话
合理设置请求头
实现重试机制
流式处理大文件
正确处理异常
使用上下文管理器
定期更新依赖
生产环境推荐配置:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def create_session():
session = requests.Session()
# 重试策略
retry_strategy = Retry(
total=3,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "OPTIONS"],
backoff_factor=1
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)
# 默认请求头
session.headers.update({
'User-Agent': 'Mozilla/5.0 ...',
'Accept-Language': 'zh-CN,zh;q=0.9'
})
return session
session = create_session()
response = session.get(url)
该配置整合了重试、连接池和请求头管理,适合大规模爬虫部署。
常见问题
与其他库对比
安全建议
〈requests与urllib对比〉
requests库在易用性上远超urllib:
特性
requests
urllib
请求构造
直观方法调用
需手动构造Request对象
参数编码
自动URL编码
需手动调用urlencode
异常处理
清晰的层次结构
异常类型分散
会话管理
内置Session对象
需手动管理Cookie
JSON处理
内置json()方法
需手动json.loads
代码量
通常少50%+
需要更多样板代码
♀requests与httpx对比
httpx是requests的现代化替代方案,支持异步请求:
特性
requests
httpx
异步支持
不支持
原生支持async/await
HTTP/2
不支持
支持HTTP/2协议
代理支持
HTTP/HTTPS/SOCKS
HTTP/HTTPS/SOCKS+代理链
生态成熟度
更成熟,文档丰富
较新,文档较少
学习曲线
平缓
需理解异步概念
对于传统爬虫项目,requests 仍是首选;当需要高并发异步请求时,可考虑迁移至httpx。
♀性能优化技巧
合理使用连接池可显著提升请求性能:
import requests
from requests.adapters import HTTPAdapter
session = requests.Session()
adapter = HTTPAdapter(pool_connections=100, pool_maxsize=100)
session.mount('http://', adapter)
session.mount('https://', adapter)
# 后续请求复用连接池
连接池参数说明:
pool_connections :连接池数量(默认10)
pool_maxsize :每个连接池的最大连接数(默认10)
在高并发场景下,建议将pool_maxsize设置为CPU核心数的2-4倍。
♀并发请求方案
多线程并发请求示例:
import threading
from queue import Queue
import requests
def worker(q, results):
while not q.empty():
url = q.get()
try:
response = requests.get(url, timeout=10)
results.append((url, response.status_code))
except Exception as e:
results.append((url, str(e)))
q.task_done()
urls = ['https://example.com/1', 'https://example.com/2', ...]
q = Queue()
results = []
for url in urls:
q.put(url)
threads = []
for _ in range(10): # 10个线程
t = threading.Thread(target=worker, args=(q, results))
t.start()
threads.append(t)
q.join()
for t in threads:
t.join()
print(results)
该方案在I/O密集型任务中表现良好,线程数应根据目标网站限制调整。
♀安全防护建议
爬虫开发中需注意:
始终验证SSL证书(避免中间人攻击)
对用户输入进行严格过滤(防止SSRF攻击)
限制重定向深度(防止重定向攻击)
使用代理池隐藏真实IP(避免被封禁)
定期更换User-Agent(模拟真实用户)
SSRF防护示例:
import ipaddress
def is_safe_url(url):
try:
# 解析URL
parsed = requests.utils.urlparse(url)
hostname = parsed.hostname
# 禁止localhost和内网地址
unsafe_hosts = ['localhost', '127.0.0.1', '0.0.0.0', '::1']
if hostname in unsafe_hosts:
return False
# 检查IP范围
try:
ip = ipaddress.ip_address(hostname)
if ip.is_private or ip.is_loopback or ip.is_link_local:
return False
except ValueError:
# hostname不是IP地址,继续检查
pass
return True
except:
return False
该函数可有效防止SSRF攻击,确保爬虫不会访问内部网络资源。
网友还关心
requests 如何处理gzip压缩响应?
如何在requests 中设置自定义SSL证书?
为什么requests 请求后响应内容为空?
requests 与selenium如何配合使用?
如何让requests 请求看起来更像真实浏览器?
requests 模块支持HTTP/2吗?
如何在requests 中处理验证码?
requests 的Session对象会话保持原理?