Requests模块说明
Requests 是使用Apache2 Licensed许可证的 HTTP 库。用 Python 编写,真正的为人类着想。
Requests 使用的是 urllib3,因此继承了它的所有特性。Requests 支持 HTTP 连接保持和连接池,支持使用 cookie 保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。现代、国际化、人性化。
Requests的文档非常完备,中文文档也相当不错。Requests能完全满足当前网络的需求,支持Python 2.6—3.x,而且能在PyPy下完美运行。
开源地址:https://github.com/kennethreitz/requests
中文文档 API:http://docs.python-requests.org/zh_CN/latest/index.html
Requests模块安装
pip install requests
Requests模块快速上手
#HTTP
请求类型
#
#get
类型
r = requests.get('
https://api.github.com/events
')
#
#
post
类型
r = requests.post("
http://httpbin.org/post
")
#
#put
类型
r = requests.put("http://httpbin.org/put")
#
#delete
类型
r = requests.delete("http://httpbin.org/delete")
#
#
head
类型
r = requests.head("http://httpbin.org/get")
#
#
options
类型
r = requests.options("http://httpbin.org/get")
#
获取响应内容
print r.content #
以字节的方式去显示,中文显示为字符
print r.text #
以文本的方式去显示
print r.json() #
以
json
格式显示
#URL
传递参数
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
#
获取
/
修改网页编码
r = requests.get('https://github.com/timeline.json')
print r.encoding
r.encoding = 'utf-8'
#
定制请求头
url = ‘http://httpbin.org/post’
headers = {'User-Agent' : '
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/71.0.3578.98 Chrome/71.0.3578.98 Safari/537.36
'}
r = requests.post(url, headers=headers)
print r.request.headers
#
复杂
post
请求
##
发送表单形式数据
payload = {'key1': 'value1', 'key2': 'value2'}
payload = (('key1', 'value1'), ('key1', 'value2'))
r = requests.post("http://httpbin.org/post"
,
data=payload
)
print r.text
##
发送
json
形式数据
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org
/
post",data=json.dumps(payload))
r = requests.post("http://httpbin.org/post"
,
json
=payload
)
print r.text
#post
多部分编码文件
url = 'http://htt
pbin.org/post
'
files = {'file': open('report.xls', 'rb')}
可以显式地设置文件名,文件类型和请求头
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
#
响应状态码
##
检测响应状态码
r = requests.get('
http://httpbin.org/
get
')
print r.status_code
##
Requests
内置的状态码查询对象
p
rint requests.codes.ok
>>200
#Informational.
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),
# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect', 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),
##发送请求返回错误状态码时,可以手动抛出异常
bad_r = requests.get('http://httpbin.org/status/500')
print(bad_r.status_code)
bad_r.raise_for_status()
>>
500
Traceback (most recent call last):
File "/home/actiontec/PycharmProjects/test/requests
模块
.py", line 6, in <module>
bad_r.raise_for_status()
File "/home/actiontec/PycharmProjects/test/venv/lib/python3.6/site-packages/requests/models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 500 Server Error: INTERNAL SERVER ERROR for url: http://httpbin.org/status/500
#
响应头
r = requests.get('http://
httpbin.org
')
print r.headers
print r.headers['Content-Type']
print r.headers.get('content-type')
#Cookies
##
访问
cookies
r = requests.get('http://www.baidu.com')
print(r.cookies) #type:RequestsCookieJar
print(dict(r.cookies))
print(r.cookies['BDORZ'])
##
发送你的
cookies
到服务器
url = 'http://htt
pbin.org
/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
print(r.text)
#
设置超时时间
r = requests.get('http://
httpbin.org
', timeout=0.1)
#
设置访问代理
proxies = {
"http": "http://10.10.10.10:8888",
"https": "http://10.10.10.100:4444",
}
r = requests.get('http://
httpbin.org
', proxies=proxies)
#重定向与请求历史
默认情况下,除了 HEAD, Requests 会自动处理所有重定向。
Github 将所有的 HTTP 请求重定向到 HTTPS:
r = requests.get('http://github.com')
print(r.url)
print(r.history)
>>
https://github.com/
[<Response [301]>]
如果你使用的是
GET
、
OPTIONS
、
POST
、
PUT
、
PATCH
或者
DELETE
,那么你可以通过
allow_redirects
参数禁用重定向处理
.
如果你使用了
HEAD
,你也可以启用重定向:
r = requests.head('http://github.com',allow_redirects=True)
#
错误与异常
遇到网络问题(如:
DNS
查询失败、拒绝连接等)时,
Requests
会抛出一个
ConnectionError
异常。
如果
HTTP
请求返回了不成功的状态码,
Response.raise_for_status()
会抛出一个
HTTPError
异常。
若请求超时,则抛出一个
Timeout
异常。
若请求超过了设定的最大重定向次数,则会抛出一个
TooManyRedirects
异常。
所有
Requests
显式抛出的异常都继承自
requests.exceptions.RequestException
。
#
会话对象
##
跨请求保持一些
cookie
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")
print(r.text)
>> '{"cookies": {"sessioncookie": "123456789"}}'
##se
ssion
也可用来为请求方法提供
默认
数据,函数参数级别的数据会和
session
级别的数据合并,如果
key
重复,函数参数级别的数据将覆盖
session
级别的数据。如果想取消
session
的某个参数,可以传递一个相同的
key
,
value
为
None
的字典。
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
##session
也可以自动关闭
with requests.session() as s:
s.get('http://httpbin.org/cookies/set/sessioncookie/12345678
')
#
响应体内容工作流
默认情况下,当你进行网络请求后,响应体会立即被下载。你可以通过
stream
参数覆盖这个行为,推迟下载响应体直到访问
Response.content
属性:
tarball_url = 'https://github.com/kennethreitz/requests/tarball/master'
r = requests.get(tarball_url, stream=True)
此时仅有响应头被下载下来了,连接保持打开状态,因此允许我们根据条件获取内容:
if int(r.headers['content-length']) < TOO_LONG:
content = r.content
...
如果设置
stream
为
True
,请求连接不会被关闭,除非读取所有数据或者调用
Response.close
可以使用
with
语句发送请求,可以保证请求一定会被关闭
.
#
流式上传
Requests
支持流式上传,这允许你发送大的数据流或文件而无需先把它们读入内存。要使用流式
上传,仅需为你的请求体提供一个类文件对象即可:
with open('massive-body') as f:
requests.post('http://some.url/streamed', data=f)