requests
是 Python 中一个非常流行的 HTTP 库,用于发送 HTTP/1.1 请求。它简洁易用,能够让你轻松地发送 GET、POST、PUT、DELETE 等请求,并且支持多种高级功能,如会话(Session)对象、HTTP(S) 代理、连接池、cookies、文件上传等。下面,我将详细介绍 requests
模块的基本用法和一些高级特性。
安装
首先,确保你已经安装了 requests
库。如果还没有安装,可以通过 pip 安装:
pip install requests
基本用法
发送 GET 请求
import requestsurl = 'http://httpbin.org/get'
response = requests.get(url)print(response.text) # 打印响应内容
print(response.status_code) # 打印 HTTP 状态码
发送 POST 请求
url = 'http://httpbin.org/post'
data = {'key': 'value'}
response = requests.post(url, data=data)print(response.text)
发送 JSON 数据
当发送 JSON 数据时,可以使用 json
参数。
url = 'http://httpbin.org/post'
json_data = {'key': 'value'}
response = requests.post(url, json=json_data)print(response.text)
响应内容
response.text
:以字符串形式返回响应体,自动根据响应的头部信息解码。response.content
:以字节形式返回响应体,未进行任何解码。response.status_code
:HTTP 响应状态码。response.headers
:响应头,以字典形式返回。response.url
:获取最终跳转的 URL(如果有重定向的话)。
会话(Session)对象
使用 Session
对象可以跨请求保持某些参数,比如 cookies、headers、认证信息等。
s = requests.Session()
s.headers.update({'Authorization': 'Bearer your_token_here'})response = s.get('http://httpbin.org/get')
print(response.text)
高级特性
认证
requests
支持多种认证方式,如 HTTP Basic Auth。
response = requests.get('http://httpbin.org/basic-auth/user/passwd', auth=('user', 'passwd'))
超时设置
可以设置请求的超时时间(秒)。
response = requests.get('http://httpbin.org/get', timeout=5)
异常处理
requests
在请求失败时会抛出 requests.exceptions.RequestException
异常,可以根据需要捕获不同类型的异常。
try:response = requests.get('http://invalid-url')response.raise_for_status() # 如果响应状态码不是 200,则抛出 HTTPError 异常
except requests.exceptions.RequestException as e:print(e)
代理设置
可以通过 proxies
参数设置代理。
proxies = {'http': 'http://10.10.1.10:3128','https': 'http://10.10.1.10:1080',
}response = requests.get('http://httpbin.org/ip', proxies=proxies)
总结
requests
库为 Python 提供了强大的 HTTP 客户端功能,支持几乎所有常见的 HTTP 请求和响应处理,是开发网络应用的理想选择。上述只是 requests
的一小部分功能,更多高级特性和用法可以查阅其官方文档。