本文共 3569 字,大约阅读时间需要 11 分钟。
Requests 是一个非转基因的 Python HTTP 库,专为安全、高效的网络请求优化而设计。无需手动构建 URL 或处理 POST 数据,它能自动管理 keep-alive 和连接池功能,是现代 web 开发的理想选择。支持 Python 2.6–2.7 和 3.3–3.7,兼容 PyPy。
以下是 Requests 的核心功能:
安装 Requests 只需运行以下命令即可:
pip install requests
该命令也会自动安装其依赖库 urllib3。
使用 Requests 发送请求非常简单。以下示例展示了如何获取 GitHub 的公共时间线:
import requestsr = requests.get('https://api.github.com/events') 查看响应状态码和内容类型:
print(r.status_code) # 200print(r.headers['content-type']) # application/json; charset=utf-8print(r.encoding) # utf-8print(r.text) # JSON 格式的响应内容
要向 URL 中传递查询参数,可以使用 `params` 字典参数:
params = { 'q': 'requests framework', 'language': 'en-US'}r = requests.get('https://google.com/search', params=params)print(r.url) # https://google.com/search?q=requests+framework&language=en-US 如果要传递包含列表的值,Requests 会自动将其编码为多个 URL 参数:
payload = { 'key1': 'value1', 'key2': ['value2', 'value3']}r = requests.get('http://httpbin.org/get', params=payload)print(r.url) # http://httpbin.org/get?key1=value1&key2=value2&key2=value3 Requests 提供了内置的 JSON 解码器:
r = requests.get('https://api.github.com/events')data = r.json() # 解码 JSON 数据print(data) 使用 Dictionary 作为 POST 数据,可以通过 `data` 参数传递:
payload = { 'user': { 'data': { 'name': 'Administrator', 'email': 'admin@example.com' } }}r = requests.post('http://httpbin.org/post', data=payload)print(r.text) # {'form': { 'user': { ... } }} 发送multipart/form-data 请求时,可以使用 `files` 参数传递文件:
files = { 'report': open('report.pdf', 'rb')}r = requests.post('http://httpbin.org/post', files=files)print(r.text) # {'files': { 'report': 'PDF 内容' }} 默认情况下,Requests 会自动处理 301、302 等重定向请求。例如,GET GitHub 终点会被重定向到其 HTTPS 终点:
r = requests.get('http://github.com')print(r.url) # https://github.com/print(r.history) # [ 可以通过 `allow_redirects` 参数禁用重定向:
r = requests.get('http://github.com', allow_redirects=False)print(r.url) # http://github.com/ 响应头可以通过字典访问:
print(r.headers) # 所有 HTTP 头部信息print(r.headers['Content-Type']) # 疑似 application/json
请求中包含的 cookies 可以通过 `cookies` 参数传递:
cookies = { 'cookie_name': 'cookie_value'}r = requests.get('http://example.com', cookies=cookies)print(r.request.headers.get('Cookie')) # Cookie: cookie_value 你也可以自行管理 Cookie Jar:
jar = requests.cookies.RequestsCookieJar()jar.set('cookie_name', 'cookie_value', domain='httpbin.org')r = requests.get('http://httpbin.org/cookies', cookies=jar)print(r.text) # {"cookies": {"cookie_name": "cookie_value"}} 可以通过 `timeout` 参数设定连接超时:
r = requests.get('http://github.com', timeout=0.5) 默认情况下不会超时。如果遇到超时错误,会抛出 `ConnectionError` 异常:
try: r = requests.get('http://github.com', timeout=0.5)except requests.exceptions.ConnectionError: print("无法连接到 GitHub") Requests 处理网络错误的异常类型包括:
ConnectionError: 网络连接错误HTTPError: 非成功 HTTP 状态码Timeout: 超时错误TooManyRedirects: 重定向次数过多RequestException: 所有其它错误类型的基类可以通过 `raise_for_status()` 检查请求是否成功:
r = requests.get('http://httpbin.org/notexist')try: r.raise_for_status()except requests.exceptions.HTTPError: print("HTTP 错误") 若有非 2xx 状态码,默认会抛出异常。
可以结合使用多种请求方法和功能:
r = requestsMethods = [ requests.get, requests.post, requests.patch, requests.delete, requests.head, requests.put]
例如,使用 HEAD 方法处理重定向:
r = requests.head('http://github.com', allow_redirects=True)print(r.url) # https://github.com/ 转载地址:http://rodpz.baihongyu.com/