本教程基于Requests
V2.18.1
文档汇编、整理。
一、简介
Requests
是一个基于urllib3
的开源Python HTTP库,项目以Apache2
协议发布。
二、安装
$ pip install requests
三、快速上手
3.1 发送请求
# 导入requests
>>> import requests
# 使用get方法请求某个URL,返回值r为Response对象。r对象包含了我们的所需信息。
>>> r = requests.get('http://httpbin.org/get')
# 类似的,其他 HTTP 请求类型:POST,PUT,DELETE,HEAD 以及 OPTIONS 用以下方式请求:
>>> r = requests.post('http://httpbin.org/post', data = {
'key':'value'})
>>> r = requests.put('http://httpbin.org/put', data = {
'key':'value'})
>>> r = requests.delete('http://httpbin.org/delete')
>>> r = requests.head('http://httpbin.org/get')
>>> r = requests.options('http://httpbin.org/get')
3.2 传递 URL 参数
Requests
允许使用params
关键字参数以字符串字典形式提供URL参数。
例如,向httpbin.org/get
传递key1=value1
和 key2=value2
,代码如下:
>>> payload = {
'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)
>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
注意:字典里值为None
的键不会被添加到 URL 的查询字符串。
此外,还可以将一个列表作为值传入。
>>> payload = {
'key1': 'value1', 'key2': ['value2', 'value3']}
3.3 响应内容
Requests
会自动解码来自服务器的响应。
请求发出后,Requests
会基于 HTTP 头部对响应的编码作出推测。当访问r.text
时,Requests
会使用其推测的编码进行解码。
>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> r.text
可以通过r.encoding
属性查询Requests
使用的编码,而且r.encoding
属性还可以改变Requests
所使用的编码。
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
3.4 二进制响应内容
以字节方式访问请求响应体:
>>> r.content
b'[{
"repository":{
"open_issues":0,"url":"https://github.com/...
Requests
会自动解码gzip
和deflate
传输编码的响应数据。
例如,以请求返回的二进制数据创建一张图片:
>>> from PIL import Image
>>> from io import BytesIO
>>> i = Image.open(BytesIO(r.content))
3.5 JSON 响应内容
Requests
内置了 JSON 解码器,可自动解码JSON格式数据:
>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{
u'repository': {
u'open_issues': 0, u'url': 'https://github.com/...
3.6 原始响应内容
通过访问 r.raw
可以获取来自服务器的原始套接字响应。 前提是在get
方法中设置了 stream=True
参数。
>>> r = requests.get('https://api.github.com/events', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
3.7 定制请求头
如果想为请求添加 HTTP 头部,只要简单地传递一个字典
对象给headers
参数就可以了。
例如,指定 content-type
>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {
'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)
注意: 定制header 的优先级低于某些特定的信息源。
例如:
- 如果在
.netrc
中设置了用户认证信息,使用headers=
设置的授权就不会生效。而如果设置了auth=
参数,.netrc
的设置就无效了。 - 如果被重定向到别的主机,授权 header 就会被删除。
- 代理授权 header 会被 URL 中提供的代理身份覆盖掉。
- 在能判断内容长度的情况下,header 的
Content-Length
会被改写。
3.8 更加复杂的 POST 请求
将字典数据传递给data
参数
例如,发送一些编码为表单形式的数据,只需简单地传递一个字典
给 data
参数。数据字典在发出请求时会自动编码为表单形式:
>>> payload = {
'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
将元组字典传递给data
参数
data
参数还可以接受元组列表
。
在表单中多个元素使用同一key
的时候,这种方式尤其有效:
>>> payload = (('key1', 'value1'), ('key1', 'value2'))
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key1": [
"value1",
"value2"
]
},
...
}
将字典数据传递给json
参数
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {
'some': 'data'}
>>> r = requests.post(url, json=payload)
3.9 POST一个多部分编码(Multipart-Encoded)的文件
>>> url = 'http://httpbin.org/post'
>>> files = {
'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
可以显式地设置文件名,文件类型和请求头:
>>> url = 'http://httpbin.org/post'
>>> files = {
'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {
'Expires': '0'})}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
3.10 响应状态码
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
为方便引用,Requests
还附带了一个内置的状态码查询对象:
>>> r.status_code == requests.codes.ok
True
如果发送了错误请求(4XX 客户端错误,或者 5XX 服务器错误响应),可以通过Response.raise_for_status()
抛出异常。
>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404
>>> bad_r.raise_for_status()
Traceback (most recent call last):
File "requests/models.py", line 832, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error
3.11 响应头
我们可以以Python 字典形式展示服务器响应头。但是这个字典比较特殊:它是仅用于 HTTP 头部。根据 RFC 2616, HTTP 头部是不区分大小写的。
>>> r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
3.12 Cookie
Requests
可以快速访问响应中包含的cookie。
>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'
使用cookies
参数可以将cookies发送到服务器。
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
在Requests
中Cookie用RequestsCookieJar
表示,它的行为和字典类似,但接口更为完整,适合跨域名跨路径使用。RequestsCookieJar
还可以传递到 Requests
中:
>>> jar = requests.cookies.RequestsCookieJar()
>>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
>>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
>>> url = 'http://httpbin.org/cookies'
>>> r = requests.get(url, cookies=jar)
>>> r.text
'{"cookies": {"tasty_cookie": "yum"}}'
3.13 重定向、请求历史
默认情况下,除了HEAD
, Requests
会自动处理所有重定向。
可以使用响应对象的history
方法来追踪重定向。
Response.history
是一个Response
对象列表,请求按照由远及近排序。
例如,Github 将所有的 HTTP 请求重定向到 HTTPS:
>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>]
如果使用的是GET
、OPTIONS
、POST
、PUT
、PATCH
或者 DELETE
,那么可以通过allow_redirects
参数禁止重定向。
>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]
如果使用了HEAD
,也可以启用重定向。
>>> r = requests.head('http://github.com', allow_redirects=True)
>>> r.url
'https://github.com/'
>>> r.history
[<Response [301]>]
3.14 超时
Requests
会在timeou
参数设定的秒数之后停止等待响应,否则程序一直等待响应。
>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
注意:timeout
仅对连接过程有效,与响应体的下载无关。
3.15 错误与异常
遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests
会抛出ConnectionError
异常。
如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status()
会抛出HTTPError
异常。
若请求超时,则抛出Timeout
异常。
若请求超过了设定的最大重定向次数,则会抛出TooManyRedirects
异常。
所有Requests
显式抛出的异常都继承自requests.exceptions.RequestException
。
四、高级教程
4.1 会话对象
会话对象能够跨请求保持某些参数。它也会在同一个Session
实例发出的所有请求之间保持 cookie, 期间使用urllib3
的connection pooling
功能。所以如果向同一主机发送多个请求,底层的 TCP 连接将会被重用,从而带来显著的性能提升。
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")
print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'
通过为会话对象的属性提供数据可以为请求方法提供缺省数据。
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({
'x-test': 'true'})
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={
'x-test2': 'true'})
会话还可以用作上下文管理器。
with requests.Session() as s:
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
4.2 请求与响应对象
任何时候进行了类似 requests.get() 的调用,你都在做两件主要的事情。其一,你在构建一个 Request 对象, 该对象将被发送到某个服务器请求或查询一些资源。其二,一旦 requests 得到一个从服务器返回的响应就会产生一个 Response 对象。该响应对象包含服务器返回的所有信息,也包含你原来创建的 Request 对象。如下是一个简单的请求,从 Wikipedia 的服务器得到一些非常重要的信息:
>>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')
如果想访问服务器返回的响应头部信息,可以使用响应对象的headers
属性。
>>> r.headers
{
'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':
'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':
'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',
'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',
'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,
must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':
'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,
MISS from cp1010.eqiad.wmnet:80'}
如果想得到发送到服务器的请求头部,可以使用响应对象的request
属性的headers
属性。
>>> r.request.headers
{
'Accept-Encoding': 'identity, deflate, compress, gzip',
'Accept': '*/*', 'User-Agent': 'python-requests/0.13.1'}
4.3 SSL 证书验证
Requests
可以为 HTTPS 请求验证 SSL 证书,就像 Web 浏览器一样。SSL 验证默认是开启的,如果证书验证失败,Requests
会抛出 SSLError
。
可以为verify
传入CA_BUNDLE
文件的路径,或者包含可信任 CA 证书文件的文件夹路径。
>>> requests.get('https://github.com', verify='/path/to/certfile')
或者将其保持在会话中:
s = requests.Session()
s.verify = '/path/to/certfile'
如果将verify
设置为False
,Requests
也能忽略对 SSL 证书的验证。
>>> requests.get('https://kennethreitz.org', verify=False)
<Response [200]>
默认情况下, verify
为True
。选项 verify
仅应用于主机证书。
4.4 客户端证书
Requests
可以指定本地证书用作客户端证书,可以是单个文件(包含密钥和证书)或一个包含两个文件路径的元组:
>>> requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))
<Response [200]>
或者保持在会话中:
s = requests.Session()
s.cert = '/path/client.cert'
4.5 CA 证书
Requests
默认附带了一套根证书,来自于 Mozilla trust store,但是它们只有在Requests
更新时才会更新。这意味着如果固定使用某一版本的Requests
,证书有可能已经太旧了。
从 Requests 2.4.0
版之后,如果系统中安装了certifi
包,Requests
会试图使用它的证书。这样用户就可以在不修改代码的情况下更新可信任证书。为了安全起见,certifi
包应该经常更新!
4.6 代理
如果需要使用代理,可以通过为请求方法提供proxies
参数来配置单个请求。
import requests
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
}
requests.get("http://example.org", proxies=proxies)
也可以通过环境变量HTTP_PROXY
和HTTPS_PROXY
来配置全局代理。
$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"
$ python
>>> import requests
>>> requests.get("http://example.org")
如果代理需要使用HTTP Basic Auth,可以使用http://user:password@host/
语法:
proxies = {
"http": "http://user:[email protected]:3128/",
}
要为特定的连接方式或者主机设置代理,使用scheme://hostname
作为 key, 它会针对指定的主机和连接方式进行匹配。
proxies = {
'http://10.20.1.128': 'http://10.10.1.10:5323'}
注意,代理 URL 必须包含连接方式。
4.7 SOCKS代理
除了基本的 HTTP 代理,Requests
还支持 SOCKS 协议的代理。
这是一个可选功能,若要使用, 需要安装第三方库。
$ pip install requests[socks]
安装好依赖以后,使用 SOCKS 代理和使用 HTTP 代理的方法一样。
proxies = {
'http': 'socks5://user:pass@host:port',
'https': 'socks5://user:pass@host:port'
}
4.8 超时(timeout)
为防止服务器不能及时响应,大部分请求都应该使用timeout
参数。在默认情况下,除非显式指定了timeout
值,Requests
是不会自动进行超时处理的。如果没有timeout
,代码可能会挂起若干分钟甚至更长时间。
连接超时指的是在客户端实现到远端机器端口的连接时,Requests
会等待的秒数。一个很好的实践方法是把连接超时设为比 3 的倍数略大的一个数值,因为 TCP 数据包重传窗口 (TCP packet retransmission window) 的默认大小是 3。
一旦客户端连接到了服务器并且发送了 HTTP 请求,读取超时指的就是客户端等待服务器发送请求的时间。(特定地,它指的是客户端要等待服务器发送字节之间的时间。在 99.9% 的情况下这指的是服务器发送第一个字节之前的时间)。
-
timeout
参数为单一值时为连接的超时时间。r = requests.get('https://github.com', timeout=5)
-
timeout
参数为二元组时,两个值分别为连接和读取的超时时间。r = requests.get('https://github.com', timeout=(3.05, 27))
-
如果远端服务器很慢,传入
None
作为timeout
值可以让Requests
永远等待。r = requests.get('https://github.com', timeout=None)
4.9 编码方式
接收响应时,Requests
会猜测响应的编码方式,只有当 HTTP 头部不存在明确指定的字符集,并且Content-Type
头部字段包含text
值时,Requests
才不去猜测编码方式。在这种情况下, RFC 2616 指定默认字符集必须是ISO-8859-1
。Requests
遵从这一规范。如果你需要一种不同的编码方式,可以手动设置Response.encoding
属性,或使用原始的Response.content
。