Python requests 模块的使用

Python requests 模块的使用

requestsPython 最流行的 HTTP 客户端,用于:

✅ 发送 GET、POST、PUT、DELETE 等请求
✅ 处理 JSON 数据
✅ 设置 Headers、Cookies、代理、认证
✅ 文件上传、下载
✅ 超时、重试、并发请求
✅ 结合 pytest 进行 API 测试

🔹 安装 requests

1
pip install requests

检查是否安装成功:

1
2
import requests
print(requests.__version__) # 输出版本号

requests 入门:基本 GET、POST 请求

🔹 发送 GET 请求

1
2
3
4
5
6
7
8
9
10
11
import requests

# 发送 GET 请求
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")

# 输出响应状态码
print(response.status_code) # 200

# 输出 JSON 响应内容
print(response.json())

🔹 发送带参数的 GET 请求

1
2
3
4
5
import requests

params = {"q": "Python", "sort": "stars"}
response = requests.get("https://api.github.com/search/repositories", params=params)
print(response.json())

🔹 发送 POST 请求

1
2
3
4
5
6
7
8
9
import requests

# 发送 POST 请求
data = {"title": "Python", "body": "requests 模块", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)

# 输出返回的 JSON 数据
print(response.json())

🔹 自定义 Headers

1
2
3
4
5
6
7
8
import requests

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
response = requests.get("https://httpbin.org/headers", headers=headers)
print(response.json())

📌 企业应用:模拟浏览器访问、避免反爬

🔹 设置 Cookies

1
2
3
4
5
import requests

cookies = {"session_id": "123456"}
response = requests.get("https://httpbin.org/cookies", cookies=cookies)
print(response.json())

📌 企业应用:模拟登录后的请求

📌 除此之外,requests 还支持put、deleteHttp请求大同小异,这里不在赘述

处理Json数据

🔹 发送 JSON 数据

1
2
3
4
5
6
7
import requests

data = {"username": "admin", "password": "123456"}
response = requests.post("https://httpbin.org/post", json=data)

print(response.json())

📌 企业应用:用户登录、API 测试

🔹 解析 JSON 响应

1
2
3
4
5
6
import requests

response = requests.get("https://jsonplaceholder.typicode.com/users/1")
data = response.json()
print(data["name"]) # 解析 JSON 数据

📌 企业应用:获取 API 返回的用户数据

处理文件

🔹 上传文件

1
2
3
4
5
import requests

files = {"file": open("test.txt", "rb")}
response = requests.post("https://httpbin.org/post", files=files)
print(response.json())

📌 企业应用:图片上传、Excel 数据上传

🔹 下载文件

1
2
3
4
5
6
7
8
import requests

response = requests.get("https://www.example.com/image.jpg")

# 保存图片
with open("image.jpg", "wb") as f:
f.write(response.content)

📌 企业应用:爬取图片、文档

超时、重试、代理

🔹 设置超时

1
2
3
4
5
6
7
8
import requests

try:
response = requests.get("https://httpbin.org/delay/5", timeout=3)
print(response.text)
except requests.Timeout:
print("请求超时!")

📌 企业应用:避免卡死,设定 API 超时时间

🔹 代理请求

1
2
3
4
5
6
7
8
9
import requests

proxies = {
"http": "http://127.0.0.1:8080",
"https": "https://127.0.0.1:8080",
}
response = requests.get("https://httpbin.org/ip", proxies=proxies)
print(response.json())

📌 企业应用:突破 IP 限制、反爬虫绕过

结合 pytest 进行 API 测试

1
2
3
4
5
6
7
8
9
10
11
import requests
import pytest

BASE_URL = "https://jsonplaceholder.typicode.com"

@pytest.mark.parametrize("user_id", [1, 2, 3])
def test_get_user(user_id):
response = requests.get(f"{BASE_URL}/users/{user_id}")
assert response.status_code == 200
assert "name" in response.json()

📌 企业应用:自动化 API 测试

结合 allure 生成 API 测试报告

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import requests
import allure

BASE_URL = "https://jsonplaceholder.typicode.com"

@allure.feature("用户信息")
@allure.story("获取用户数据")
def test_get_user():
with allure.step("发送 API 请求"):
response = requests.get(f"{BASE_URL}/users/1")

with allure.step("校验返回状态码"):
assert response.status_code == 200

with allure.step("校验 JSON 数据"):
assert "name" in response.json()

allure.attach(response.text, name="API Response", attachment_type=allure.attachment_type.JSON)

📌 企业应用:生成美观的 API 测试报告

总结

功能 代码示例
发送 GET 请求 requests.get(url)
发送 POST 请求 requests.post(url, json=data)
设置 Headers wronrequests.get(url, headers=headers)
超时设置 requests.get(url, timeout=3)
代理请求 requests.get(url, proxies=proxies)
文件上传 requests.post(url, files=files)
文件下载 requests.get(url).content
自动重试 requests.Session().mount("https://", adapter)
API 测试 pytest + requests
测试报告 pytest + allure

Python requests 模块的使用
https://dreamshao.github.io/2025/03/27/python常见request的使用/
作者
Yun Shao
发布于
2025年3月27日
许可协议