Python Requests文档阅读笔记
学习库还是得从文档下手,Python Requests Library
以下内容均摘录总结于该文档,所以具体部分可以参考文档。
快速上手
- 使用前别忘记导入
Requests
模块
import requests
发送请求
本部分即告知你本库能够完成各种HTTP请求类型,毕。
此处涉及HTTP协议的一些知识,我走马观花式搜索了一些资料,大致了解一下,了解一下
GET
和POST
,搜索引擎能找到资料很多,比如HTTP协议详解Requests
库能够实现各种HTTP请求类型,如下:
r = requests.get('https://github.com/timeline.json')
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("http://httpbin.org/get")
传递URL参数
首先说一下
URL
的查询字符串的含义,查询字符串置于地址后,以?
分隔,例如httpbin.org/get?key = val
,?
后便是查询字符串,可以这么理解它:比如说该位置是用来获取资源的,但是我们如果想对资源有选择的获取,那么紧跟后的查询字符串就是限制条件,我们获取key
值为val
的资源。Requests
库允许你使用param
关键字参数,以一个字符串字典来提供这些参数,举例来说,如果你想传递key1 = value1
和key2 = value2
到httpbin.org/get
,那么你可以使用如下代码:
payload = {'key1':'value1','key2':'value2'}
r = requests.get("http://httpbin.org/get",params = payload)
- 通过打印该URL,你能看到URL被正确编码:
print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
- 字典里
value
为None的不会被添加到其中,另外你还可以将一个列表作为值传入:
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
响应内容
- 通过
GET
方法我们可以读取服务器相应的内容,如
import requests
r = requests.get('https://github.com/timeline.json')
r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...
Requests
会自动解码来自服务器的内容,但你使用r.text
后,它会使用其推测的文本编码,你可以找出他的编码,并能够使用r.encoding =
来改变:
r.encoding
'utf-8'
r.encoding = 'ISO-8859-1'
二进制相应内容\JSON响应内容\原始相应内容
- 以字节(二进制)的方式请求响应体,
r.content
- JSON相应内容,
r.json()
- 原始响应内容,
r.raw
,并且在get方法中设置了stream = True
,如
r = requests.get('https://github.com/timeline.json', stream=True)
r.raw
r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
定制请求头
- 如果你想为请求添加
HTTP
头部,只要简单地传递一个dict
给headers
参数就可以了。
url = 'https://api.github.com/some/endpoint'
h = {'user-agent':'my-app/0.0.1'}
r = requests.get(url,headers = h)
更加复杂的POST请求
- 如果你想要发送一些编码为表单形式的数据——非常像一个HTML表单。要实现这个,只需简单地传递一个字典给
data
参数,你的数据字典在发出请求时会自动编码为表单形式:
payload = {'key1':value,'key2':'value2'}
r = requests.post("http://httpbin.org/post,data = payload")
print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
- 还可以为
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)
响应头
- 我们可以查看以一个Python字典形式展示的服务器响应头:
r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
- 但是这个字典比较特殊:它是仅为HTTP头部而生的,因此是大小写不敏感的,在python中这部分也变得不敏感了,因此我们可以使用任意大小写形式来访问这些响应头字段:
r.headers['Content-Type']
'application/json'
r.headers.get('content-type')
'application/json'
Cookie
- 如果某个响应中包含一些
cookie
,你可以快速访问它们:
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name']
'example_cookie_value'
- 要想发送你的
cookie
到服务器,可以使用cookie
参数:
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
对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。
r = requests.get('http://github.com')
r.url
'https://github.com/'
r.status_code
200
r.history
[<Response [301]>]
- 如果你使用了
HEAD
,你也可以启用重定向
r = requests.head('http://github.com', allow_redirects=True)
r.url
'https://github.com/'
r.history
[<Response [301]>]
超时
- 你可以告诉
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
仅对连接过程有效,与响应体的下载无关,timeout
并不是整个下载相应的时间限制,而是如果服务器在timeout
秒内没有应答,将会引发一个异常。
错误与异常
- 遇到网络问题(DNS查询失败等),Requests会抛出一个
ConnectionError
异常。 - 如果HTTP请求返回了不成功的状态码,
Response.raise_for_status()
会抛出一个HTTPError
异常。 - 如果请求超时,则会抛出一个
Timeout
异常。 - 如果请求超过了设定最大重定向次数,则会抛出一个
TooManyRedirects
异常。