Python requests 模块:轻松玩转网络请求的实用工具
在日常开发中,我们经常需要与网络服务打交道——比如调用天气 API 获取实时数据,或者从某个网站抓取公开信息。这时候,Python 自带的 urllib 虽然能用,但写起来繁琐且不够直观。而 requests 模块的出现,就像给开发者配了一辆“顺风车”,让网络请求变得简单、优雅又高效。
Python requests 模块 是目前最流行的 HTTP 库之一,它的设计哲学是“人类可读”,语法简洁,功能强大。无论你是初学者还是有一定经验的开发者,只要掌握它,就能快速完成大部分网络交互任务。今天我们就来一步步拆解这个神器,从安装到实战,让你真正“用起来”。
安装与基础用法
首先,你需要确保已经安装了 requests 模块。如果你的环境中还没有,可以通过 pip 命令轻松安装:
pip install requests
安装完成后,我们就可以在 Python 脚本中导入并使用它了。
import requests
response = requests.get("https://www.baidu.com")
print("状态码:", response.status_code)
print("响应内容(前200字):", response.text[:200])
💡 注释说明:
requests.get()是发起 GET 请求的最常用方法,参数是目标 URL。response.status_code返回服务器的 HTTP 状态码,比如 200 表示成功,404 表示页面不存在。response.text是响应的文本内容,适用于 HTML、JSON 等文本格式。
这个例子就像是你打开浏览器输入网址,requests 就是你“自动点击”访问的行为,而 response 就是网页返回的结果。
发送不同类型的请求
除了 GET,HTTP 协议还支持 POST、PUT、DELETE 等多种请求方式。requests 模块为每种方式都提供了对应的方法。
GET 请求:获取数据
GET 请求用于从服务器获取信息,比如查询用户信息、获取天气数据。
import requests
url = "https://api.openweathermap.org/data/2.5/weather"
params = {
"q": "Beijing", # 城市名
"appid": "YOUR_API_KEY", # 请替换为你的实际 API Key
"units": "metric" # 使用摄氏度
}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json() # 将 JSON 格式响应转换为 Python 字典
print("当前温度:", data["main"]["temp"], "°C")
else:
print("请求失败,状态码:", response.status_code)
💡 注释说明:
params参数会自动拼接到 URL 后面,形成类似?q=Beijing&appid=xxx&units=metric的形式。response.json()是一个便捷方法,用于解析 JSON 响应。它会自动处理编码和格式转换。
POST 请求:提交数据
POST 请求常用于提交表单、上传文件或创建资源。
import requests
url = "https://httpbin.org/post" # 一个用于测试的免费 API
data = {
"username": "alice",
"password": "123456"
}
response = requests.post(url, data=data)
print("服务器返回的数据:", response.json())
💡 注释说明:
data参数会以application/x-www-form-urlencoded的方式发送。- 如果你想发送 JSON 数据,应使用
json=data参数,而不是data=data。
处理请求头与超时设置
在真实项目中,很多 API 要求你设置特定的请求头(headers),比如 User-Agent、Authorization 等。requests 模块允许你轻松自定义这些信息。
import requests
url = "https://httpbin.org/headers"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Authorization": "Bearer your_token_here", # 如果是需要鉴权的 API
"Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
print("服务器收到的请求头:", response.json()["headers"])
💡 注释说明:
headers字典用于设置 HTTP 请求头。User-Agent常用于伪装成浏览器,避免被反爬机制拦截。Authorization用于身份验证,如 JWT Token。
此外,网络请求可能因为网络延迟或服务器无响应而长时间卡住。这时设置超时时间就非常关键。
import requests
try:
response = requests.get("https://httpbin.org/delay/5", timeout=3)
print("请求成功,响应时间:", response.elapsed.total_seconds(), "秒")
except requests.exceptions.Timeout:
print("请求超时,超过 3 秒未响应")
except requests.exceptions.RequestException as e:
print("请求发生异常:", e)
💡 注释说明:
timeout=3表示最多等待 3 秒,超时则抛出异常。- 使用
try-except捕获异常,让程序更健壮。
处理响应数据与编码问题
服务器返回的数据可能是 HTML、JSON、XML,甚至二进制文件(如图片、PDF)。requests 提供了多种方式来处理它们。
解析 JSON 数据
import requests
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
if response.headers.get("Content-Type") == "application/json":
post_data = response.json()
print("标题:", post_data["title"])
print("内容:", post_data["body"])
else:
print("返回内容不是 JSON 格式")
💡 注释说明:
response.json()会自动解析 JSON 字符串,返回 Python 字典或列表。- 建议先检查
Content-Type头,避免对非 JSON 数据调用.json()导致错误。
保存二进制文件(如图片)
import requests
url = "https://httpbin.org/image/jpeg"
response = requests.get(url, stream=True) # 使用 stream=True 避免一次性加载全部数据
with open("downloaded_image.jpg", "wb") as f:
for chunk in response.iter_content(chunk_size=1024):
f.write(chunk)
print("图片已保存为 downloaded_image.jpg")
💡 注释说明:
stream=True表示分块下载,适合大文件,节省内存。response.iter_content(chunk_size=1024)按 1KB 一块读取,防止内存溢出。
实际应用场景:爬取天气信息
我们来做一个完整的实战案例:从公开 API 获取北京的天气信息,并输出简要摘要。
import requests
import json
def get_weather(city="Beijing", api_key="YOUR_API_KEY"):
"""
获取指定城市的天气信息
参数:
city: 城市名称,如 "Beijing"
api_key: OpenWeatherMap 的 API 密钥
返回:
天气摘要字符串
"""
url = "https://api.openweathermap.org/data/2.5/weather"
params = {
"q": city,
"appid": api_key,
"units": "metric"
}
try:
response = requests.get(url, params=params, timeout=5)
if response.status_code == 200:
data = response.json()
temp = data["main"]["temp"]
desc = data["weather"][0]["description"]
humidity = data["main"]["humidity"]
wind_speed = data["wind"]["speed"]
summary = f"""
🌤️ 北京天气摘要:
温度:{temp}°C
天气:{desc}
湿度:{humidity}%
风速:{wind_speed} m/s
"""
return summary
else:
return f"获取天气失败,状态码:{response.status_code}"
except requests.exceptions.RequestException as e:
return f"请求异常:{e}"
print(get_weather("Beijing", "your_actual_api_key_here"))
💡 注释说明:
- 该函数封装了完整的请求逻辑,包含错误处理和返回格式化。
- 你可以将
api_key替换为你在 OpenWeatherMap 注册后获得的密钥,免费账户可使用。
常见问题与最佳实践
| 问题 | 原因 | 解决方案 |
|---|---|---|
requests.exceptions.ConnectionError |
网络不通或服务器拒绝连接 | 检查网络、代理设置,或使用 timeout 防止卡死 |
response.json() 报错 |
响应不是 JSON 格式 | 先检查 response.text 或 response.headers |
| 请求被拒绝(如 403) | 缺少 User-Agent 或 IP 被封 |
添加合理的请求头,避免高频请求 |
| 中文乱码 | 服务器未正确设置编码 | 使用 response.encoding = 'utf-8' 手动指定 |
✅ 最佳实践建议:
- 所有网络请求都应加上
timeout。- 使用
try-except包裹请求逻辑。- 对于频繁请求,考虑使用
session对象复用连接。- 避免在生产环境中硬编码 API 密钥。
总结
Python requests 模块 是现代 Python 开发中不可或缺的工具。它把复杂、繁琐的网络交互简化为几行代码,让开发者能专注于业务逻辑本身。无论是调用 RESTful API、抓取网页数据,还是上传文件,requests 都能轻松应对。
从今天开始,别再用 urllib 写冗长的请求代码了。学会使用 requests,你的开发效率将得到质的提升。记住:简洁的代码 = 可读性强 + 易维护 + 减少 bug。
不管你是初学者还是中级开发者,只要掌握 Python requests 模块 的核心用法,就能在实际项目中游刃有余。多练多用,你会发现,网络请求原来也可以这么简单。