Python—requests模块
requests
模块是 Python 中一个非常流行的用于发送 HTTP 请求的第三方库。它提供了一个简单且直观的 API 来处理各种 HTTP 请求,如 GET、POST、PUT、DELETE 等。下面是一些关于 requests
模块的基本用法和示例。
安装 requests
模块
首先,你需要安装 requests
模块。如果你还没有安装,可以使用以下命令通过 pip 安装:
pip install requests
基本用法
发送 GET 请求
import requests
response = requests.get('https://api.example.com/data')
# 检查响应状态码
print(response.status_code)
# 获取响应内容(文本形式)
print(response.text)
# 获取响应内容(JSON 格式,如果响应内容是 JSON)
print(response.json())
发送 POST 请求
import requests
url = 'https://api.example.com/submit'
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=data)
print(response.status_code)
print(response.json())
发送带有请求头的请求
import requests
url = 'https://api.example.com/data'
headers = {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
}
response = requests.get(url, headers=headers)
print(response.status_code)
print(response.json())
发送带有查询参数的请求
import requests
url = 'https://api.example.com/search'
params = {'q': 'python requests', 'sort': 'asc'}
response = requests.get(url, params=params)
print(response.url) # 查看最终的 URL
print(response.json())
处理响应
response
对象包含了很多有用的信息:
response.status_code
:HTTP 响应状态码。response.text
:响应内容的字符串形式。response.json()
:将响应内容解析为 JSON 对象(如果内容是 JSON 格式)。response.content
:响应内容的二进制形式。response.headers
:响应头信息。response.cookies
:从响应中提取的 cookies。
异常处理
requests
模块还提供了异常处理机制,常见的异常有 requests.exceptions.RequestException
,你可以捕获这个异常来处理请求失败的情况:
import requests
from requests.exceptions import RequestException
try:
response = requests.get('https://api.example.com/data')
response.raise_for_status() # 如果响应状态码不是 200,会抛出 HTTPError 异常
print(response.json())
except RequestException as e:
print(f"An error occurred: {e}")
高级用法
使用会话(Session)
会话对象允许你跨请求保持某些参数,比如 cookies 和 headers。
import requests
session = requests.Session()
# 设置会话级别的 headers
session.headers.update({'Authorization': 'Bearer YOUR_ACCESS_TOKEN'})
# 发送请求
response = session.get('https://api.example.com/data')
print(response.json())
超时设置
你可以为请求设置超时时间,以防止请求无限期地挂起:
import requests
try:
response = requests.get('https://api.example.com/data', timeout=5) # 5 秒超时
print(response.json())
except requests.exceptions.Timeout:
print("The request timed out")
总结
requests
模块是一个非常强大且易于使用的 HTTP 客户端库。它简化了发送 HTTP 请求和处理响应的过程,使开发者能够专注于业务逻辑而不是底层的网络细节。通过掌握这些基本用法,你可以轻松地在 Python 应用中集成 HTTP 请求功能。