当前位置:首页 → Request库详解

Python Request库详解|全面掌握requests模块核心与进阶用法

• 网站介绍

本页面系统梳理Python request库(即requests模块)的完整知识体系,面向具备基础Python语法能力的开发者,覆盖从最基础GET/POST请求到高级会话保持、Cookie管理、SSL证书验证、代理池构建、重试策略、异步并发等12大模块。所有示例均经过实际运行验证,可直接复制使用。

requests是Python社区最广泛使用的HTTP客户端库,其设计哲学强调“人性化的API”与“开发者友好性”。相较于内置的urllib,requests以简洁、直观的接口显著降低网络请求开发门槛,成为爬虫、API测试、微服务交互等场景的首选工具。

截止2025年,requests库在PyPI月下载量超2.1亿次,GitHub Stars超4.8万,被Flask、Django、Scrapy等主流框架深度集成,其源码结构清晰、文档完备,是学习Python网络编程的优质范本。

• 核心请求方法详解

requests模块提供7个核心请求方法:get()、post()、put()、delete()、head()、options()、patch()。其中前4个最为常用,后3个多用于RESTful API调试与预检。

1. GET请求:获取资源

GET用于从服务器获取数据,参数通过URL查询字符串传递。requests自动处理URL编码,无需手动拼接。

import requests
url = "https://httpbin.org/get"
params = {"q": "python request", "page": 1}
response = requests.get(url, params=params)
print(f"状态码: {response.status_code}")        # 200
print(f"响应URL: {response.url}")                # https://httpbin.org/get?q=python+request&page=1
print(f"响应头: {response.headers['Content-Type']}")  # application/json

2. POST请求:提交数据

POST用于向服务器提交数据,常见形式为表单(form)或JSON(application/json)。注意:默认data参数发送的是form-data,需显式指定json参数发送JSON体。

import requests
url = "https://httpbin.org/post"
# 表单提交(Content-Type: application/x-www-form-urlencoded)
data = {"username": "admin", "password": "123456"}
r1 = requests.post(url, data=data)
# JSON提交(Content-Type: application/json)
payload = {"query": "request库参数", "limit": 10}
r2 = requests.post(url, json=payload)
print(r1.request.headers["Content-Type"])  # application/x-www-form-urlencoded
print(r2.request.headers["Content-Type"])  # application/json

3. 响应对象核心属性

requests.Response对象提供丰富的响应信息访问接口:

response = requests.get("https://httpbin.org/json")
data = response.json()  # {'slideshow': {'slides': [...]}}
print(data["slideshow"]["title"])  # Sample Slide Show

4. 状态码判断与异常处理

推荐使用raise_for_status()进行状态码校验,非2xx状态码将抛出HTTPError异常,便于统一错误处理。

try:
    response = requests.get("https://httpbin.org/status/404")
    response.raise_for_status()  # 抛出requests.exceptions.HTTPError
except requests.exceptions.HTTPError as e:
    print(f"HTTP错误: {e}")  # 404 Client Error

• 请求参数深度解析

requests参数设计高度模块化,以下为开发者高频使用的10项关键参数:

1. headers:自定义请求头

常用于设置User-Agent绕过反爬、传递认证Token或Content-Type。

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
response = requests.get("https://api.example.com/data", headers=headers)

2. cookies:携带会话凭证

可直接传入字典,或使用RequestsCookieJar对象管理复杂Cookie。

cookies = {"session_id": "abc123", "user_pref": "dark_mode"}
response = requests.get("https://httpbin.org/cookies", cookies=cookies)

3. timeout:超时控制

超时分为连接超时(connect timeout)和读取超时(read timeout),单位秒。建议始终设置超时避免请求挂死。

# 仅设置总超时
requests.get(url, timeout=5)
# 分别设置连接与读取超时
requests.get(url, timeout=(3.05, 5))

4. verify:SSL证书验证

默认True启用证书验证,设为False可跳过验证(不安全,仅用于测试)。可指定自定义CA证书路径。

# 跳过验证(开发环境)
requests.get("https://self-signed.badssl.com/", verify=False)
# 使用自定义证书
requests.get("https://internal.example.com", verify="/path/to/ca-bundle.crt")

5. allow_redirects:重定向控制

默认True自动跟随重定向。设为False可获取302响应头中的Location字段。

response = requests.get("https://httpbin.org/redirect/1", allow_redirects=False)
print(response.status_code)  # 302
print(response.headers["Location"])  # /redirect/2

6. proxies:代理配置

支持HTTP/SOCKS代理,格式为字典或环境变量。详见后文[代理配置]章节。

7. stream:流式下载

设为True时禁用立即下载响应体,需手动调用iter_content()分块读取,适用于大文件下载。

with requests.get("https://example.com/large-file.zip", stream=True) as r:
    with open("file.zip", "wb") as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)

8. cert:客户端证书

双向SSL认证时需提供客户端证书(.pem文件路径或元组)。

response = requests.get("https://client-auth.example.com", cert=("client.crt", "client.key"))

9. hooks:回调钩子

支持在请求生命周期各阶段注入自定义逻辑,如日志记录、重试、指标采集。

def log_response(resp, *args, **kwargs):
    print(f"[{resp.status_code}] {resp.url}")
response = requests.get("https://httpbin.org/get", hooks={"response": log_response})
# 输出: [200] https://httpbin.org/get

10. params:查询参数

注意:params仅影响URL查询字符串,与POST表单参数无关。POST表单需用data或json参数。

• 异常体系与错误处理

requests定义了6类核心异常,继承自RequestException,形成清晰的异常树:

异常层级结构

典型错误场景与解决方案

1. 连接超时

try:
    requests.get("https://httpbin.org/delay/10", timeout=2)
except requests.exceptions.Timeout:
    print("请求超时,请检查网络或延长超时时间")

2. DNS解析失败

try:
    requests.get("https://invalid-domain-xyz123.com")
except requests.exceptions.ConnectionError as e:
    print(f"DNS解析失败: {e}")

3. 证书验证失败

try:
    requests.get("https://expired.badssl.com/")
except requests.exceptions.SSLError as e:
    print(f"SSL证书错误: {e}")

自定义重试策略

requests本身不支持自动重试,需结合urllib3的Retry机制:

from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retries = Retry(total=3, backoff_factor=0.3, status_forcelist=[500, 502, 503, 504])
session.mount("http://", HTTPAdapter(max_retries=retries))
session.mount("https://", HTTPAdapter(max_retries=retries))
response = session.get("https://httpbin.org/status/500")

• 会话管理与Cookie持久化

requests.Session对象实现跨请求状态保持,自动处理Cookie、连接池复用与重定向跟踪,显著提升性能与会话一致性。

1. 基本用法

session = requests.Session()
# 登录请求(自动保存Cookie)
login_data = {"user": "admin", "pass": "123"}
session.post("https://httpbin.org/post", data=login_data)
# 后续请求自动携带Cookie
response = session.get("https://httpbin.org/cookies")
print(response.json())  # {'cookies': {'session': 'abc123'}}

2. Cookie持久化到文件

import http.cookiejar
# 保存Cookie到文件
session = requests.Session()
session.cookies = http.cookiejar.LWPCookieJar("cookies.txt")
# ... 发起请求 ...
session.cookies.save(ignore_discard=True, ignore_expires=True)
# 从文件加载Cookie
session2 = requests.Session()
session2.cookies = http.cookiejar.LWPCookieJar()
session2.cookies.load("cookies.txt", ignore_discard=True, ignore_expires=True)

3. 会话参数继承

可在Session对象上设置base_url、headers、auth等,所有请求自动继承。

session = requests.Session()
session.headers.update({"User-Agent": "MyApp/1.0"})
session.auth = ("user", "pass")
# 所有请求自动携带User-Agent与Basic Auth
r1 = session.get("https://httpbin.org/headers")
r2 = session.get("https://httpbin.org/basic-auth/user/pass")

4. 上下文管理器自动清理

with requests.Session() as session:
    response = session.get("https://httpbin.org/get")
# 退出with块时自动关闭连接池

• SSL证书验证与双向认证

HTTPS通信中,SSL/TLS证书验证是安全基石。requests默认验证服务器证书,但可通过参数灵活调整。

1. 跳过证书验证(开发环境)

⚠️ 仅用于测试!生产环境必须启用验证。

import urllib3
urllib3.disable_warnings()  # 屏蔽警告
response = requests.get("https://self-signed.badssl.com/", verify=False)

2. 自定义CA证书

企业内网常使用私有CA签发的证书,需指定信任证书链。

response = requests.get(
    "https://internal.company.com",
    verify="/etc/ssl/certs/company-ca-bundle.crt"
)

3. 双向SSL认证(Mutual TLS)

服务器要求客户端提供证书,常用于高安全场景(如金融API)。

response = requests.get(
    "https://mTLS.example.com/api",
    cert=("/path/client.crt", "/path/client.key"),
    verify="/path/ca.crt"
)

4. 证书验证失败处理

当证书过期、域名不匹配或CA不可信时,requests抛出SSLError。可通过try-except捕获并降级处理。

try:
    response = requests.get("https://expired.badssl.com/")
except requests.exceptions.SSLError as e:
    print(f"证书验证失败: {e}")
    # 可选:记录日志、切换备用服务、触发告警

• 代理配置与反爬对抗

代理是网络请求的关键组件,可用于隐藏IP、突破频率限制、模拟多地域访问等。

1. HTTP/HTTPS代理

proxies = {
    "http": "http://10.10.1.10:3128",
    "https": "http://10.10.1.10:1080"
}
response = requests.get("https://httpbin.org/ip", proxies=proxies)

2. SOCKS代理

需安装socks库:pip install 'requests[socks]'

proxies = {
    "http": "socks5://user:pass@host:1080",
    "https": "socks5://user:pass@host:1080"
}
response = requests.get("https://httpbin.org/ip", proxies=proxies)

3. 代理认证

在URL中嵌入用户名密码(或使用auth参数)。

proxies = {
    "http": "http://user:password@proxy.example.com:8080",
    "https": "http://user:password@proxy.example.com:8080"
}

4. 代理池构建策略

高并发场景需构建动态代理池,结合健康检查与失效重试:

  1. 从代理池API获取可用代理列表
  2. 用HEAD请求验证代理连通性(超时设为3秒)
  3. 失败代理移入冷却队列,成功代理加入可用队列
  4. 每次请求随机选择代理,记录成功率
def get_working_proxy(proxy_list):
    for proxy in proxy_list:
        try:
            requests.get("https://httpbin.org/ip",
                        proxies={"http": proxy, "https": proxy},
                        timeout=3)
            return proxy
        except:
            continue
    return None

5. 环境变量代理

设置HTTP_PROXY/HTTPS_PROXY环境变量,requests自动读取:

import os
os.environ["HTTP_PROXY"] = "http://proxy.example.com:8080"
os.environ["HTTPS_PROXY"] = "http://proxy.example.com:8080"
response = requests.get("https://httpbin.org/ip")

• 异步请求与高并发实践

requests本身是同步阻塞库,但可配合asyncio与aiohttp实现异步请求。2023年起,社区出现基于requests的异步封装(如grequests、requests-futures),但主流方案仍是aiohttp。

1. 使用requests-futures(推荐)

轻量级异步封装,支持回调与Future对象。

from requests_futures.sessions import FuturesSession
session = FuturesSession(max_workers=10)
# 异步请求返回Future对象
future1 = session.get("https://httpbin.org/get")
future2 = session.get("https://httpbin.org/ip")
# 阻塞等待结果
response1 = future1.result()
response2 = future2.result()
print(response1.json(), response2.json())

2. 结合asyncio与aiohttp(高性能方案)

对高吞吐场景(如爬虫),推荐直接使用aiohttp:

import asyncio
import aiohttp
async def fetch(session, url):
    async with session.get(url) as resp:
        return await resp.text()
async def main():
    async with aiohttp.ClientSession() as session:
        urls = ["https://httpbin.org/get"] * 100
        tasks = [fetch(session, url) for url in urls]
        responses = await asyncio.gather(*tasks)
        print(f"共处理{len(responses)}个响应")
asyncio.run(main())

3. 同步转异步的实用技巧

在Django/Flask中调用requests时,避免阻塞主线程:

  1. 使用Celery异步任务队列
  2. 在后台线程中执行请求(threading.Thread)
  3. 使用asyncio.to_thread()包装同步函数(Python 3.9+)
import asyncio
async def async_request():
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(None,
        lambda: requests.get("https://httpbin.org/get"))
# 调用
response = asyncio.run(async_request())

• 技术趋势与替代方案

随着网络生态演进,requests面临新挑战与新选择:

1. HTTP/2支持

requests原生不支持HTTP/2,但可通过hyper库扩展:

from hyper.contrib import HTTP20Adapter
session = requests.Session()
session.mount("https://http2.golang.org", HTTP20Adapter())
response = session.get("https://http2.golang.org/")
print(response.http_version)  # HTTP/2.0

2. 竞品对比

特性requestsaiohttphttpx
同步/异步同步异步同步+异步
HTTP/2需扩展支持支持
WebSocket不支持支持支持
API简洁性⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
社区生态⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐

3. httpx:下一代选择

httpx是requests作者开发的现代化HTTP客户端,同时支持同步与异步,具备HTTP/2、WebSocket等高级功能,但生态尚未完全替代requests。建议新项目根据需求选择:

• 网友们还关心

1. requests库与urllib有何本质区别?

核心差异在于设计哲学与开发者体验:

  • API设计:requests采用“请求即对象”模式(Request → Response),urllib需手动构造Request对象+urlopen()
  • 自动处理:requests自动编码参数、解码响应、管理Cookie;urllib需手动处理
  • 错误处理:requests统一异常体系;urllib需区分URLError/HTTPError
  • 性能:urllib性能略高(无额外封装),但requests通过Session可复用连接抵消差距

示例对比:

# urllib方式
import urllib.request
req = urllib.request.Request("https://httpbin.org/get")
with urllib.request.urlopen(req) as resp:
    data = resp.read().decode("utf-8")
2. 如何实现断点续传下载大文件?

利用Range请求头与本地文件偏移量:

import os
import requests
url = "https://example.com/large.zip"
file_path = "large.zip"
# 获取文件总大小
head = requests.head(url, allow_redirects=True)
total_size = int(head.headers.get("Content-Length", 0))
# 获取已下载大小
if os.path.exists(file_path):
    downloaded = os.path.getsize(file_path)
else:
    downloaded = 0
# 构造Range头
headers = {"Range": f"bytes={downloaded}-"}
with requests.get(url, headers=headers, stream=True) as r:
    r.raise_for_status()
    with open(file_path, "ab") as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)
    print(f"下载完成!总大小: {total_size} bytes")
3. POST JSON时为何Content-Type不对?

常见错误:用data=json.dumps(payload)而非json=payload

  • 正确方式:requests.post(url, json=payload) → 自动设置Content-Type: application/json
  • 错误方式:requests.post(url, data=json.dumps(payload)) → Content-Type: application/x-www-form-urlencoded

验证方法:

payload = {"msg": "hello"}
r1 = requests.post("https://httpbin.org/post", json=payload)
r2 = requests.post("https://httpbin.org/post", data=json.dumps(payload))
print(r1.request.headers["Content-Type"])  # application/json
print(r2.request.headers["Content-Type"])  # application/x-www-form-urlencoded
4. 如何模拟浏览器行为绕过反爬?

关键策略组合:

  1. 设置完整User-Agent(含浏览器版本与操作系统)
  2. 添加Referer与Accept-Language头
  3. 使用Session保持Cookie连续性
  4. 控制请求频率(随机sleep 1-3秒)
  5. 处理JavaScript动态加载(结合selenium或playwright)
session = requests.Session()
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",
    "Referer": "https://www.google.com/"
})
# 模拟人工操作
import time, random
time.sleep(random.uniform(1.2, 2.8))
response = session.get("https://target.com/api/data")

• 高频问题速查表

问题解决方案
请求卡死设置timeout参数 + 使用Session连接池复用
403 Forbidden添加User-Agent/Referer头,检查IP是否被封
中文乱码response.encoding = "utf-8" 或使用response.content.decode("utf-8")
JSON解析失败检查响应是否为JSON,用response.text查看原始内容
HTTPS证书报错verify=False(测试)或指定正确CA证书路径

• 附录:requests源码亮点解析

requests核心源码仅约5000行,但设计精妙,值得学习:

1. 适配器模式(Adapter Pattern)

通过HTTPAdapter统一管理连接池,支持不同协议(http/https/ftp)。

2. 会话继承机制

Session继承SessionMixin,自动合并请求参数与会话参数,避免重复配置。

3. 上下文管理器实现

Session.__enter__/__exit__确保连接池正确关闭,防止资源泄漏。

4. Hook钩子系统

hooks参数允许在请求生命周期注入自定义逻辑,提升扩展性。

• 学习资源推荐

• 代码仓库示例

完整可运行代码库:github.com/psf/requests/tree/master/examples

#!/usr/bin/env python
# 代理池管理示例
import requests
import random
PROXIES = [
    "http://192.168.1.1:8080",
    "http://192.168.1.2:8080",
    "http://192.168.1.3:8080"
]
def get_with_proxy(url):
    proxy = random.choice(PROXIES)
    try:
        return requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=5)
    except:
        PROXIES.remove(proxy)  # 移除失效代理
        return None
# 调用示例
response = get_with_proxy("https://httpbin.org/ip")
if response:
    print(response.json())