Python中requests模块功能
以下是对requests模块功能的基本介绍。
一、简介
Requests模块是第三方模块,需要预先安装,requests模块在python内置模块的基础上进行了高度的封装,从而使得python进行网络请求时,变得更加简洁和人性化。
二、模块内容:
__version__版本
_internal_utils--内部使用函数
adapters--传输适配器
api--应用程序编程接口
auth--身份验证处理程序
certs--CA证书包
compat--处理Python 2和Python 3
cookies--储存在用户本地终端上的数据
exceptions--请求异常
help--bug报告助手
hooks--响应挂钩
models--强制请求
packages--请求包
sessions--请求对话
status_codes--状态码
structures--请求数据结构
utils--公用函数
三、requests库的方法
1、requests.request()设置请求格式
基本格式reques.request(method, url, **kwargs) 设置请求格式。
①method方法: request对象的:``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``方法。
②url地址: 爬取的网页地址。
③ params参数:为字典或字节序列,作为参数增加到链接url中。
④data参数: 字典,字节序列或文件对象,作为请求的内容,与requests.post()进行联用。
⑤json: JSON格式的数据,作为Request的内容,与requests.post()进行联用。
⑥headers: 字典,HTTP定制头(模拟浏览器进行访问)。
⑦cookies: 字典或CpplieJar,Request中的cookie。
⑧files: 字典类型,传输文件。
⑨auth:元祖,支持HTTP认证功能。
⑩timeout: 设定超时时间,秒为单位。
(11)allow_redirects: 启用/禁用GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD,默认为True,重定向开关。
(12) proxies:字典类型,设定访问代理服务器,可以增加登陆认证。
(13)verify: True/False,默认为True,认证SSL证书开关。
(14)stream: True/False,默认为True,获取内容立即下载开关。
(15)cert: 本地SSL证书路径。
2、requests.get()请求获取url位置的资源
基本格式requestsget(url, params=None, **kwargs)请求获取url位置的资源
参数同上,(略)
3、requests.head()请求获取url位置的资源的响应报告,及获得头部信息
基本格式requests.head(url, **kwargs)
参数同上,(略)
但,allow_redirects '没有提供,它将被设置为' False '与默认的:meth: ' request '行为相反。
4、requests.post()请求获取url位置的资源后附加用户新的数据
基本格式requets.post(url, data=None, json=None, **kwargs)
参数同上,(略)
注意以参数data,json使用。
5、requests.put()请求获取url位置储存一个资源,覆盖原url位置资源
基本格式requets.put(url, data=None, **kwargs)
参数同上,(略)
6、requests.patch()请求局部更新url位置资源,及改变该处资源的部分内容
基本格式requets.patch(url, data=None, **kwargs)
参数同上,(略)
7、requests.delete()请求删除url位置储存的资源
基本格式requets.delete(url, **kwargs):发送 DELETE 请求。 返回响应对象。
参数同上,(略)
使用注意事项:
1、获取云端资源用get(),head()
2、把自己资源放入云端用put() post() patch()
3、删除现有资源delete()
4、用url对资源位置的定义用patch()与put(),它们的区别patch可以对于局部修好,put是全部覆盖
四、requests请求响应对象response的属性
1、r.status_code:HTTP请求返回的状态,200表示成功,404表示失败,还有其他的也代表失败
2、r.text:HTTP响应内容转换成字符串格式,获得响应体文本信息
3、r.content:HTTP响应内容转换成二进制格式,获得响应体的二进制,主要一般用于音频文件,视频文件等等用于二进制保存。
4、r.encoding:从HTTP header中猜测响应内容,返回值的解码格式
5、r.apparent_encoding:从内容中分析响应内容的编码方式(备选编码方式),reuqests模块自动检测返回值信息,给你返回一个合适的解码格式。
6、r.url:返回值的url
7、r.json:其本质json.loads(response.text)
8、r.cookie:响应体的cookie
9、r.headers:响应体的请求头
10、r.history:响应体的历史。这个稍微理解下,你以为是访问的你给的那个url,其实它重定向了另一个地址去访问。他会留下他重定向之前的url并且以一个列表套对象的格式给你返回值。
注意:r.encoding与r.apparent_encoding区别
r.encoding:如果header中不存在charset,则默认编码为ISO-8859-1
r.apparent_encoding :根据内容来匹配出合适的编码
apparent_encoding比encoding更加准确的展示编码方式
五、requests请求的异常
1、requests.ConnectionError:网络连接错误异常,如DNS查询失败、拒绝连接等
2、requests.HTTPErroHTTP:错误异常
3、requests.URLRequired:URL缺失异常
4、requests.TooManyRedirects:超过最大重定向次数,产生重定向异常
5、requests.ConnectTimeout:连接远程服务器超时异常
6、requests.Timeout:请求URL超时,产生超时异常
如果在r.status_code不是200时候,我们可以r.raise_for_status(),如果不是200,引发HTTPError异常
六、status_code状态码
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',),
# 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'),