什么是 requests 模块?
requests 模块是 Python 第三方库,用于向网页(服务器)发送 HTTP 请求并获取响应,它比 Python 内置的 urllib 模块更简洁、更人性化,极大地简化了网络请求的编写。

核心特点:
- 简洁易用:API 设计非常直观,几行代码就能完成复杂的请求。
- 功能强大:支持所有 HTTP 方法(GET, POST, PUT, DELETE, HEAD, OPTIONS 等)。
- 自动解码:自动处理响应内容的编码,让你能直接获取文本或二进制数据。
- 会话管理:通过
Session对象可以跨请求保持某些参数(如 cookies)。 - 完善的文档:拥有非常清晰和全面的官方文档。
安装
在使用之前,你需要先安装它,打开你的终端或命令行工具,运行:
pip install requests
核心概念:Response 对象
当你使用 requests 发送一个请求后,它会返回一个 Response 对象,这个对象包含了服务器对你的请求的所有响应信息,主要的属性有:
response.status_code:HTTP 状态码(如 200 表示成功,404 表示未找到)。response.text的文本形式。response.content的二进制形式。response.json():如果响应内容是 JSON 格式,这个方法会将其解析为 Python 字典。response.headers:响应头信息,是一个类字典对象。response.cookies:响应中的 cookies。response.url:请求的最终 URL(可能会因为重定向而改变)。response.history:请求的重定向历史。
常用 HTTP 请求方法
GET 请求:获取数据
这是最常见的请求类型,用于从服务器获取资源。

示例1:获取网页文本
import requests
try:
# 发送 GET 请求到百度首页
response = requests.get('https://www.baidu.com')
# 检查请求是否成功 (状态码为 200)
if response.status_code == 200:
# 打印响应文本(前 500 个字符)
print("请求成功!")
print("网页内容(前500字符):")
print(response.text[:500])
else:
print(f"请求失败,状态码: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"发生错误: {e}")
示例2:带参数的 GET 请求
向 API 发送请求时,通常需要查询参数。
import requests
# API 端点
url = 'https://api.github.com/search/repositories'
# 查询参数,字典形式
params = {
'q': 'requests+language:python',
'sort': 'stars',
'order': 'desc'
}
try:
response = requests.get(url, params=params)
if response.status_code == 200:
# 使用 .json() 方法解析 JSON 响应
data = response.json()
print(f"找到 {data['total_count']} 个相关仓库")
# 打印第一个仓库的名称
if data['items']:
print(f"排名第一的仓库是: {data['items'][0]['name']}")
else:
print(f"请求失败,状态码: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"发生错误: {e}")
POST 请求:提交数据
用于向服务器提交数据,例如提交表单、上传文件等。

示例1:提交表单数据
import requests
# 目标 URL
url = 'https://httpbin.org/post'
# 要提交的数据,字典形式
payload = {
'username': 'john_doe',
'password': 'secret123'
}
try:
response = requests.post(url, data=payload)
if response.status_code == 200:
# httpbin.org 会返回你发送的数据
print("服务器收到的数据:")
print(response.json()['form'])
else:
print(f"请求失败,状态码: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"发生错误: {e}")
示例2:提交 JSON 数据
很多现代 API 要求你发送 JSON 格式的数据。
import requests
import json # 虽然 requests 会自动处理,但显式导入也是好习惯
url = 'https://httpbin.org/post'
# 要发送的 JSON 数据
json_data = {
'name': 'Alice',
'age': 30,
'is_student': False
}
try:
# 使用 json 参数会自动设置 Content-Type 为 application/json
response = requests.post(url, json=json_data)
if response.status_code == 200:
print("服务器收到的 JSON 数据:")
print(response.json()['json'])
else:
print(f"请求失败,状态码: {response.status_code}")
except requests.exceptions.RequestException as e:
print(f"发生错误: {e}")
高级用法
自定义请求头
有些网站需要特定的请求头(如 User-Agent)才能正常访问。
import requests
url = 'https://www.example.com'
headers = {
'User-Agent': 'MyCoolApp/1.0 (myemail@example.com)',
'Accept-Language': 'en-US,en;q=0.9'
}
response = requests.get(url, headers=headers)
print(response.text)
处理响应内容编码
requests 通常能自动判断编码,但有时也会出错,你可以手动指定。
from requests.exceptions import HTTPError
import requests
url = 'https://example.com/some-encoding-issue-page'
try:
response = requests.get(url)
# requests 会自动解码 response.text
# 如果编码有问题,可以手动设置
# response.encoding = 'utf-8' # 或 'gbk', 'iso-8859-1' 等
print(response.text)
except HTTPError as http_err:
print(f"HTTP 错误发生: {http_err}")
except Exception as err:
print(f"其他错误发生: {err}")
超时设置
为了避免请求长时间挂起,你应该设置超时时间。
import requests
try:
# timeout 接受一个 (连接超时, 读取超时) 的元组,或者一个总的秒数
response = requests.get('https://www.google.com', timeout=5) # 5秒后超时
print("请求成功!")
except requests.exceptions.Timeout:
print("请求超时!")
except requests.exceptions.RequestException as e:
print(f"发生错误: {e}")
会话对象 (Session)
Session 对象可以让你在多个请求之间保持某些参数,cookies,这对于需要登录的网站尤其有用。
import requests
# 创建一个 Session 对象
with requests.Session() as session:
# 第一次请求,可能服务器会返回一个 session cookie
session.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
# 第二次请求,会带上之前设置的 cookie
response = session.get('https://httpbin.org/cookies')
print("第二次请求的响应内容:")
print(response.json())
异常处理
requests 定义了一套丰富的异常类,用于处理网络请求中可能出现的各种问题。
requests.exceptions.ConnectionError:网络连接问题(如 DNS 查询失败、拒绝连接)。requests.exceptions.HTTPError:HTTP 错误响应(状态码 4xx 或 5xx)。requests.exceptions.Timeout:请求超时。requests.exceptions.TooManyRedirects:重定向过多。requests.exceptions.RequestException:所有requests异常的基类,可以用来捕获所有异常。
最佳实践:总是用 try...except 包裹你的请求。
import requests
from requests.exceptions import RequestException
url = 'https://some-non-existent-site.com'
try:
response = requests.get(url, timeout=10)
# 如果状态码不是 2xx,会抛出 HTTPError
response.raise_for_status()
print(response.text)
except RequestException as e:
print(f"请求出错了: {e}")
总结与最佳实践
| 功能 | 方法/示例 | 说明 |
|---|---|---|
| 发送请求 | requests.get(url), requests.post(url, data=payload) |
根据方法选择对应的函数。 |
| 传递参数 | requests.get(url, params={'key': 'value'}) |
GET 请求的查询参数。 |
| 提交数据 | requests.post(url, data=form_data) |
表单数据。requests.post(url, json=json_data) |
| 自定义请求头 | requests.get(url, headers={'User-Agent': '...'}) |
模拟浏览器或添加其他信息。 |
| 处理响应 | response.status_code, response.text, response.json() |
检查状态码,获取文本或解析 JSON。 |
| 设置超时 | requests.get(url, timeout=5) |
防止请求无限期挂起。 |
| 保持会话 | with requests.Session() as session: |
在多个请求间保持 cookies。 |
| 错误处理 | try...except requests.exceptions.RequestException |
健壮的代码必须处理网络错误。 |
requests 模块是 Python 工具箱中不可或缺的一员,掌握了它,你就拥有了与任何公开 API 或网站进行交互的能力。
