
Requests is the only Non-GMO HTTP library for Python, safe for human consumption.
目录
#1. Requests 安装
##1.1 使用conda安装
$ conda install request
##1.2 使用源码安装
$ git clone git://github.com/requests/requests.git
$ cd requests
$ pip install .
#2. Request使用
##2.1 创建 Request
>>> import requests
# requests.get(): 获取网页的主要方法
>>> r = requests.get('https://api.github.com/events')
这一步后,我们获得了一个叫r的响应;
>>> r
Out[6]: <Response [200]> #200表示请求响应成功
##2.2 传递 URL 参数
Requests 有一个参数 params
,可以向URL传递参数.下面例子是向http://httpbin.org/get
;一个键值对传递后,结果是httpbin.org/get?key=val。
>>> 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
>>> 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
##2.3 响应内容
我们可以读取服务器响应的内容, 再次以GitHub时间轴为例:
>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...
Requests会自动解析享用的内容;但Requests一般是基于HTTP 头部的编码类型解析网页内容;使用 r.text
就可以访问解析的具体内容。
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1' #r.encoding自定义编码类型
##2.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))
##2.5JSON 响应内容
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/...
##2.6 原始响应内容
来自服务器的原始套接字响应保存在r.raw中;这也需要在请求时设置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'
将文本输出到文件:
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
##2.7 定制请求头
如果你想为请求添加 HTTP 头部,只要简单地传递一个 dict
给 headers
参数就可以了。
>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)
##2.8 更复杂的 POST 请求
向网页提交类似HTML格式内容,只需要将字典内容传递给参数data;提交的字典内容会被自动解析:
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("https://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
data参数指向的字典中,每个键可以有多个值。
>>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]
>>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)
>>> payload_dict = {'key1': ['value1', 'value2']}
>>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)
>>> print(r1.text)
{
...
"form": {
"key1": [
"value1",
"value2"
]
},
...
}
>>> r1.text == r2.text
True
如果传给data的数据的不是字典是字符串,字符串会直接post。
如果是使用json格式信息:
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, json=payload)
2.9 提交一个多种编码的文件
>>> url = 'https://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
##2.10 响应状态码
建立request之后,我们需要检查response状态:
>>> r = requests.get('https://httpbin.org/get')
>>> r.status_code
200
一种更简单的检查方式:
>>> r.status_code == requests.codes.ok
True
对于错误请求,可以使用[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
##2.11 响应头信息
以字典的形式查看服务器相应之后获取的网页头信息
>>> r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
访问header中指定信息:
>>> r.headers['Content-Type']
'application/json'
>>> r.headers.get('content-type')
'application/json'
##2.12 Cookies
如果response中包含Cookies,访问方式如下:
>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'
发送自己的cookies至服务器,使用参数 cookies
:
>>> url = 'https://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
##2.13 重定向和日志
默认情况下,Requests会自动处理除HEAD外的所有重定向;并且通过响应日志可以追溯重定向。 Response.history
列表中包含响应对象,并且这些响应对象依据请求时间排序。
例子,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 or 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]>]
##2.14 超时设定
设定一个等待响应的时间阈值,使用timeout
参数:
>>> requests.get('https://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)
##2.15 错误和异常
-
requests.RequestException
: 请求异常 -
requests.ConnectionError
: 网络问题(DNS failure, refused connection,etc) -
requests.HTTPError
: HTTP错误异常 -
requests.URLRequired
: URL错误 -
requests.TooManyRedirects
: 请求数目超过设定的最大重定向数目 -
requests.ConnectTimeout
: 连接超时 -
requests.ReadTimeout
: 在规定时间内,服务器没有传输任何数据 -
requests.Timeout
: 请求超时
#3. 参考
[Requests Quickstart]http://docs.python-requests.org/en/master/user/quickstart/#response-headers
网友评论