>>> r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
这个响应头是以 python 的字典形式展示的,但是它是仅为HTTP头部而生的一个字典,它不区分大小写;
所以,我们也可以:
>>> r.headers['Content-Type']
'application/json'
>>> r.headers.get('content-type')
'application/json'
响应中含有 cookie 的访问:
>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'
要想自己发送 cookie 到服务器,可以使用cookies
参数:
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
cookie 的返回对象为 RequestsCookieJar;
它的行为和字典类似,但是接口更为完整;
它可以跨域名跨路径使用,还可以把 Cookie Jar 传到 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"}}'
默认情况下,除了 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]>]
timeout
参数可以设定秒数时间后停止响应等待时间;
基本上所有生产代码都需要这一参数,如果不使用,程序可能永远失去响应;
>>> 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 仅对连接过程有效,与响应体的下载无关。 timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常(更精确地说,是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时)If no timeout is specified explicitly, requests do not time out.
ConnectionError 异常:遇到网络问题(如:DNS 查询失败、拒绝连接等);
HTTPError 异常:返回不成功的状态码,Response.raise_for_status() 会将其抛出;
Timeout 异常:请求超时;
TooManyRedirects 异常:请求超过了设定的最大重定向次数;
所有Requests显式抛出的异常都继承 自 requests.exceptions.RequestException;
【初级篇--完】
本文为Larwas原创文章,转载无需和我联系,但请注明来自larwas博客 https://larwas.com
最新评论