Python Requests快速入门


快速上手

                                                      转载地址:http://blog.csdn.net/iloveyin/article/details/21444613

  迫不及待了吗?本页内容为如何入门Requests提供了很好的指引。其假设你已经安装了Requests。如果还没有, 去 安装 一节看看吧。

首先,确认一下:

  • Requests 已安装
  • Requests是 最新的

  让我们从一些简单的示例开始吧。

Python字典形式展示的服务器响应头:



>>> r.headers
{
    'status': '200 OK',
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json; charset=utf-8'
}



  但是这个字典比较特殊:它是仅为HTTP头部而生的。根据 RFC 2616 , HTTP头部是大小写不敏感的。

  因此,我们可以使用任意大写形式来访问这些响应头字段:



>>> r.headers['Content-Type']
'application/json; charset=utf-8'

>>> r.headers.get('content-type')
'application/json; charset=utf-8'



如果某个响应头字段不存在,那么它的默认值为 None



>>> r.headers['X-Random']
None





Cookies

  如果某个响应中包含一些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"}}'





重定向与请求历史

使用GET或OPTIONS时,Requests会自动处理位置重定向。

Github将所有的HTTP请求重定向到HTTPS。可以使用响应对象的 history 方法来追踪重定向。 我们来看看Github做了什么:



>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[301]>]
  Response.history 是一个:class:Request 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。

  如果你使用的是GET或OPTIONS,那么你可以通过 allow_redirects 参数禁用重定向处理:



>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]



  如果你使用的是POST,PUT,PATCH,DELETE或HEAD,你也可以启用重定向:



>>> r = requests.post('http://github.com', allow_redirects=True)
>>> r.url
'https://github.com/'
>>> r.history
[301]>]





超时

你可以告诉requests在经过以 timeout 参数设定的秒数时间之后停止等待响应:



>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
  File "", line 1, in 
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)




注:

timeout 仅对连接过程有效,与响应体的下载无关。

错误与异常

遇到网络问题(如:DNS查询失败、拒绝连接等)时,Requests会抛出一个ConnectionError 异常。

遇到罕见的无效HTTP响应时,Requests则会抛出一个 HTTPError 异常。

若请求超时,则抛出一个 Timeout 异常。

若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。

所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。