Requests HTTP 库:人性化的 HTTP 请求

FreeGuideOnline 最新 2026-06-16

Requests 库:让 HTTP 请求更人性化

Requests 是 Python 生态中最受欢迎的 HTTP 库之一,它以“HTTP for Humans”为设计理念,将复杂的网络请求封装成简洁、直观的接口。无论是初学者还是资深开发者,都能通过 Requests 快速完成各类 HTTP 操作,而不必陷入底层细节的泥潭。本教程将带你从零开始,全面掌握 Requests 的核心用法。

1. 环境准备与安装

在开始之前,请确保你的环境中已经安装了 Python(推荐 3.7 及以上版本)。Requests 的安装非常简单,只需使用 pip:

pip install requests

安装完成后,可以在交互式环境中导入验证:

import requests
print(requests.__version__)

如果输出版本号,则说明安装成功。

2. 发送第一个请求

Requests 为每一种 HTTP 方法都提供了对应的函数,命名与 HTTP 动词完全一致,这让代码的可读性极强。最常用的是 requests.get(),用于获取网页内容。

import requests

response = requests.get('https://httpbin.org/get')
print(response.text)  # 打印响应体文本

只需一行代码,就完成了完整的 GET 请求。response 对象包含了服务器返回的所有信息,我们将在后文详细拆解。

3. 请求参数传递

3.1 URL 查询参数

对于 GET 请求,你经常需要携带查询字符串。Requests 允许你通过 params 参数以字典形式传入,它会自动编码并拼接到 URL 中。

params = {'key1': 'value1', 'key2': ['value2', 'value3']}
response = requests.get('https://httpbin.org/get', params=params)
print(response.url)  # 查看最终编码后的 URL

3.2 请求体与表单数据

  • 表单数据data 参数用于发送 application/x-www-form-urlencoded 格式的数据。
data = {'username': 'test', 'password': '123'}
response = requests.post('https://httpbin.org/post', data=data)
  • JSON 数据:使用 json 参数可以直接传入字典,Requests 会自动设置 Content-Type: application/json 并进行序列化。
json_data = {'name': 'Alice', 'age': 25}
response = requests.post('https://httpbin.org/post', json=json_data)
  • 原始数据:如果需要发送 XML、纯文本等,直接将字符串赋值给 data 参数,并手动设置 Content-Type
headers = {'Content-Type': 'application/xml'}
xml = '<user><name>Alice</name></user>'
response = requests.post('https://httpbin.org/post', data=xml, headers=headers)

4. 处理响应

请求返回的 Response 对象像一本打开的书,所有信息一目了然。

属性/方法 说明
response.status_code HTTP 状态码,如 200、404
response.text 响应体文本(自动解码)
response.content 响应体字节内容,适合图片、文件等非文本资源
response.json() 将 JSON 响应体解析为 Python 字典(如果内容不是 JSON 会报错)
response.headers 响应头字典,不区分大小写
response.url 最终请求的 URL(可能发生重定向)
response.encoding 响应内容的编码,可手动修改来避免乱码

实战示例:

response = requests.get('https://api.github.com')
if response.status_code == 200:
    data = response.json()
    print(f"GitHub API 当前用户数:{data['user_url']}")
else:
    print(f"请求失败,状态码:{response.status_code}")

很多接口需要携带特定的头信息或身份凭证,Requests 让这些操作同样自然。

5.1 请求头 headers

headers = {
    'User-Agent': 'MyApp/1.0',
    'Authorization': 'Bearer your_token_here'
}
response = requests.get('https://httpbin.org/headers', headers=headers)
print(response.json()['headers'])

你可以直接在 cookies 参数中传入字典,或者在响应中读取服务器返回的 Cookie。

# 在请求中发送 Cookie
cookies = {'session_id': 'abcd1234'}
r = requests.get('https://httpbin.org/cookies', cookies=cookies)

# 从响应中获取 Cookie
r = requests.get('https://example.com')
print(r.cookies['session_id'])  # 注意可能需要服务器有设置

6. 会话保持:让请求记住你

如果你需要多次请求并保持同一个会话(包括 Cookie、连接池等),应该使用 Session 对象。它可以自动处理 Cookie 持久化和连接复用,显著提升效率。

with requests.Session() as session:
    session.headers.update({'User-Agent': 'MySession'})
    # 第一次请求,服务器设置 Cookie
    session.get('https://httpbin.org/cookies/set/sessioncookie/hello')
    # 第二次请求,自动携带上次返回的 Cookie
    r = session.get('https://httpbin.org/cookies')
    print(r.json())  # 可以看到 cookie 已被携带

7. 超时与重试

网络请求永远要做好“意外”的准备。设置超时和重试是保障程序健壮性的重要手段。

  • 超时设置timeout 参数可以指定等待服务器响应的秒数,超过时间就会抛出异常。
try:
    response = requests.get('https://httpbin.org/delay/5', timeout=2)
except requests.Timeout:
    print("请求超时,请稍后重试")
  • 重试机制:结合 requests.adapters.HTTPAdapterurllib3 的重试模块,可以优雅地实现自动重试。
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

session = requests.Session()
retries = Retry(total=3, backoff_factor=1, status_forcelist=[500, 502, 503, 504])
adapter = HTTPAdapter(max_retries=retries)
session.mount('http://', adapter)
session.mount('https://', adapter)
# 后续使用 session 发请求,若遇到指定状态码会自动重试

8. 文件上传与下载

Requests 让文件操作也变得直观。

  • 文件上传:使用 files 参数,支持普通文件、元组指定文件名和类型。
files = {'file': open('report.txt', 'rb')}
response = requests.post('https://httpbin.org/post', files=files)
# 或者更精确:
files = {'file': ('report.txt', open('report.txt', 'rb'), 'text/plain')}
  • 大文件下载:对于大文件,应使用流式下载,避免一次性加载内存。
response = requests.get('https://example.com/bigfile.zip', stream=True)
with open('bigfile.zip', 'wb') as f:
    for chunk in response.iter_content(chunk_size=8192):
        f.write(chunk)

9. 异常处理

Requests 提供了清晰的异常层次,方便你针对不同错误做出响应。

常见异常:

  • requests.ConnectionError:网络连接问题(如 DNS 错误、拒绝连接)
  • requests.HTTPError:非 2xx 状态码(需要调用 raise_for_status() 或手动检查)
  • requests.Timeout:请求超时
  • requests.TooManyRedirects:重定向次数过多
  • requests.RequestException:所有异常的基类,可用于兜底捕获

推荐实践:

try:
    response = requests.get('https://example.com', timeout=5)
    response.raise_for_status()  # 如果状态码不是 200,会抛出 HTTPError
except requests.HTTPError as e:
    print(f"HTTP 错误:{e}")
except requests.ConnectionError:
    print("无法连接到服务器")
except requests.Timeout:
    print("请求超时")
except requests.RequestException as e:
    print(f"请求异常:{e}")

10. 结语:为什么选择 Requests?

Requests 的人性化体现在每一个细节:API 设计与 HTTP 概念高度一致,让你凭直觉就能写出正确的代码;丰富的参数和自动处理(编码、Cookie、重定向等)消除了大量样板代码;完善的文档和社区更是学习与排错的强力后盾。

无论是简单的数据抓取、API 调用,还是复杂的会话管理和文件处理,Requests 都能帮助你用最少的代码完成最多的工作。此刻开始,将 Requests 纳入你的工具箱,让 HTTP 通信变得简单而优雅。