1. 初识 Requests
1.1 什么是 Requests?
Requests 是一个基于 Python 的第三方 HTTP 库,以简洁优雅的 API 设计著称,能够轻松发送 HTTP/1.1 请求。相比 Python 内置的 urllib
模块,Requests 具有以下优势:
- 代码更简洁直观
- 自动处理 URL 编码和参数拼接
- 支持文件上传、Cookie 持久化、连接池等高级功能
- 提供完善的错误处理机制
它是与 Web API 交互、爬虫开发、服务端测试等场景的利器。
1.2 安装 Requests
通过 pip
一键安装:
pip install requests
验证安装:
import requests
print(requests.__version__) # 输出版本号,如 2.31.0
1.3 发送第一个请求
import requests
response = requests.get("https://httpbin.org/get")
print(f"状态码: {response.status_code}")
print(f"响应内容: {response.text[:100]}...") # 截取前100字符
运行结果示例:
状态码: 200
响应内容: {
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
...
2. 基础用法
2.1 GET 请求
2.1.1 基本 GET 请求
url = "https://httpbin.org/get"
response = requests.get(url)
# 关键属性
print(response.url) # 实际请求的URL
print(response.status_code) # HTTP状态码
print(response.headers) # 响应头信息
print(response.json()) # 自动解析JSON响应
2.1.2 带参数的 GET 请求
方式一:手动拼接 URL
params = {"key1": "value1", "key2": "value2"}
url = f"https://httpbin.org/get?key1={params['key1']}&key2={params['key2']}"
方式二:使用 params
参数(推荐)
params = {"page": 2, "limit": 10}
response = requests.get("https://httpbin.org/get", params=params)
print(response.url) # 自动生成带参数的URL
2.2 POST 请求
2.2.1 基本 POST 请求
url = "https://httpbin.org/post"
response = requests.post(url)
print(response.json()["url"]) # 输出响应中的URL字段
2.2.2 带数据的 POST 请求
发送表单数据(application/x-www-form-urlencoded)
data = {"username": "admin", "password": "secret"}
response = requests.post("https://httpbin.org/post", data=data)
print(response.json()["form"]) # 查看表单数据
发送 JSON 数据(application/json)
import json
headers = {"Content-Type": "application/json"}
data = {"name": "Alice", "age": 30}
response = requests.post(
"https://httpbin.org/post",
json=data, # 自动序列化为JSON
# 等价于:data=json.dumps(data), headers=headers
)
print(response.json()["json"]) # 查看解析后的JSON
2.3 其他 HTTP 方法
方法 | 描述 | 示例代码 |
---|---|---|
PUT | 替换目标资源 | requests.put(url, data=data) |
DELETE | 删除指定资源 | requests.delete(url) |
HEAD | 获取响应头(无Body) | requests.head(url) |
OPTIONS | 查询服务器支持的通信选项 | requests.options(url) |
完整示例:
# PUT 请求
response = requests.put("https://httpbin.org/put", data={"key": "value"})
# DELETE 请求
response = requests.delete("https://httpbin.org/delete")
# HEAD 请求
response = requests.head("https://httpbin.org/get")
print(response.headers)
# OPTIONS 请求
response = requests.options("https://httpbin.org")
print(response.headers.get("allow")) # 查看允许的方法
关键特性总结表
功能 | 实现方式 |
---|---|
发送请求 | requests.get() / post() 等 |
URL 参数处理 | params 字典参数 |
表单提交 | data 字典参数 |
JSON 数据提交 | json 字典参数 |
自定义请求头 | headers 字典参数 |
响应内容解析 | .text / .json() |
通过本文,您已掌握 Requests 库的核心操作。后续可深入学习会话管理、文件上传、代理设置等进阶功能。