http://cn.python-requests.org/zh_CN/latest/user/quickstart.html 快速上手
学习文档并记录下过程,希望自己能理解更多的知识
开始时导入模块:
>>> import requests
发送请求
试着获取网页的内容:
>>> r = requests.get('https://github.com/timeline.json')
注:https的网址会需要去验证证书,如上网址返回:/Library/Python/2.7/site-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
>>> print r
<Response [410]>
可以看出现在我们得到了一个名叫r的 Respons 对象。从这个对象中我们可以获取想要的信息。
Requsts简便的API意味着所有的HTTP请求类型都是显而易见的。例如如下些的POST、PUT、DELETE、HEAD、以及OPTION的请求类型:
>>> r = requests.post("http://httpbin.org/post")
>>> r = requests.put("http://httpbin.org/put")
>>> r = requests.delete("http://httpbin.org/delete")
>>> r = requests.head("http://httpbin.org/get")
>>> r = requests.options("
为URL传递参数
人工创建URL时候数据会以 键/值 对的形式置于URL中,跟在一个问号后面。例如:httpbin.org/get?key=val
。
Requests允许你使用params关键字参数,以一个字典来提供这些参数。举例来说,如果你想传递key1=value1
和 key2=value2
到 httpbin.org/get
,那么你可以使用如下代码:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)
>>> r.url
http://httpbin.org/get?key2=value2&key1=value1
输出的url可以看出URL已经被正确编码。注:payload中字典的值为None时,该键不会被添加到URL的查询字符中。
响应内容
>>> r = requests.get('http://httpbin.org/get')
>>> r.text
u'{\n "args": {}, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.7.0 CPython/2.7.6 Darwin/14.1.0"\n }, \n "origin": "202.134.124.242", \n "url": "http://httpbin.org/get"\n}\n'
我们会读取服务器响应的内容。如上所示。Requests会自动解码来自服务器的内容。大多数unicode字符集都能被无缝的解码。
请求发出后,Requests会基于HTTP头部对响应的编码做出有根据的推测。比如当你访问r.text的时候,Requests会使用其推测的文本编码。你可以找出Requests使用了什么编码,并且可以使用r.encoding属性来改变它:
>>> r.encoding
'ISO-8859-1'
>>> r.encoding ='utf-8'
>>> r.encoding
'utf-8'
每次访问r.text的时候,Requests都将会使用r.encoding的新值。
二进制响应内容
这个例子没有成功完成,暂时跳过。
JSON响应内容
Requests中也有一个内置的JSON解码器,用于处理JSON数据:
>>> r = requests.get('http://data.btcchina.com/data/ticker')
>>> r.json()
{u'ticker': {u'sell': u'1533.41', u'buy': u'1533.27', u'last': u'1533.41', u'vol': u'19893.28110000', u'prev_close': u'1527.52', u'vwap': u'1532.61', u'high': u'1558.68', u'low': u'1519.75', u'date': 1441609063, u'open': u'1527.52'}}
如果JSON解码失败,r.json就会抛出一个异常。例如,相应内容是 401 (Unauthorized) ,尝试访问 r.json
将会抛出 ValueError:No JSON object could be decoded
异常。
原始响应内容(极少用到)
>>> r = requests.get('https://github.com/timeline.json', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x10a153610>
>>> r.raw.read
<bound method HTTPResponse.read of <requests.packages.urllib3.response.HTTPResponse object at 0x10a153610>>
>>> r.raw.read()
''
定制请求头
如果想为请求添加HTTP头部,只要简单传递一个dict给headers参数就可以了。
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)
更加复杂的POST请求
一般想要发送一些编码为表单形式的数据非常像一个HTML表单。要实现这个,只需要传递一个字典给data参数。数据字典在发出请求时会自动编码为表单形式:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print r.text
{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.7.0 CPython/2.7.6 Darwin/14.1.0"
},
"json": null,
"origin": "202.134.124.242",
"url": "http://httpbin.org/post"
}
响应头
>>> r.headers
{'content-length': '449', 'server': 'nginx', 'connection': 'keep-alive',
'access-control-allow-credentials': 'true', 'date': 'Mon, 07 Sep 2015 07:54:13 GMT',
'access-control-allow-origin': '*', 'content-type': 'application/json'}
HTTP头部是大小写不敏感的。因此,我们可以使用任意大写形式来访问这些响应头字段:
>>> r.headers.get('content-type')
'application/json'
>>> r.headers['Content-Type']
'application/json'
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"}}'
重定向与请求历史
默认情况下,除了HEAD,Requests会自动处理所有重定向。
可以使用响应对象response的history方法来追踪重定向。
>>> type(r.history)
<type 'list'>
>>> type(r)
<class 'requests.models.Response'>
可以看出,Response.history是一个列表,为了完成请求而创建了这些对象。这个对象列表按照时间由远到近的请求进行排序。例如:
>>> r = requests.get('http://github.com')
>>> r.url'https://github.com/'
>>> r.status_code200
>>> r.history
[<Response [301]>]
如果你使用的是GET, OPTIONS, POST, PUT, PATCH 或者 DELETE,,那么你可以通过 allow_redirects
参数禁用重定向处理:
>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code301
>>> r.history[]
如果你使用的是HEAD,你也可以启用重定向,设置allow_redirects=True.
超时
你可以告诉requests在经过以 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
仅对连接过程有效,与响应体的下载无关。
错误与异常
遇到网络问题(如:DNS查询失败、拒绝连接等)时,Requests会抛出一个 ConnectionError
异常。
遇到罕见的无效HTTP响应时,Requests则会抛出一个 HTTPError
异常。
若请求超时,则抛出一个 Timeout
异常。
若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects
异常。
所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException
。