您现在的位置是:首页 > 文章详情

Python requests库

日期:2019-01-15点击:360

requests是一个用于在程序中进行http协议下的get和post请求的库。

安装

easy_install requests 

或者用

pip install requests 

安装好之后在交互模式下运行

>>> import requests >>> dir(requests) ['ConnectionError', 'HTTPError', 'NullHandler', 'PreparedRequest', 'Request', 'RequestException', 'Response', 'Session', 'Timeout', 'TooManyRedirects', 'URLRequired', '__author__', '__build__', '__builtins__', '__copyright__', '__doc__', '__file__', '__license__', '__name__', '__package__', '__path__', '__title__', '__version__', 'adapters', 'api', 'auth', 'certs', 'codes', 'compat', 'cookies', 'delete', 'exceptions', 'get', 'head', 'hooks', 'logging', 'models', 'options', 'packages', 'patch', 'post', 'put', 'request', 'session', 'sessions', 'status_codes', 'structures', 'utils'] 

从上面的列表中可以看出在http中常用到的getcookiespost等都赫然在目。

get请求

>>> r = requests.get("http://www.hiekay.com") 

得到一个请求的实例然后

>>> r.cookies <RequestsCookieJar[]> 

这个网站对客户端没有写任何cookies内容。换一个看看

>>> r = requests.get("http://www.baidu.com") >>> r.cookies <<class 'requests.cookies.RequestsCookieJar'>[Cookie(version=0, name='PHPSESSID', value='buqj70k7f9rrg51emsvatveda2', port=None, port_specified=False, domain='www.baidu.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]> 

原来这样呀。继续还有别的属性可以看看。

>>> r.headers {'Content-Encoding': 'gzip', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Server': 'bfe/1.0.8.18', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:24 GMT', 'Connection': 'Keep-Alive', 'Pragma': 'no-cache', 'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Date': 'Wed, 16 Jan 2019 07:42:13 GMT', 'Content-Type': 'text/html'} >>> r.encoding 'UTF-8' >>> r.status_code 200 

下面这个比较长是网页的内容仅仅截取显示部分

>>> print r.text <!DOCTYPE html> <!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç¾åº¦ä¸ä¸ï¼ä½ å°±ç¥é</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç¾åº¦ä¸ä¸ class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ°é»</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å°å¾</a> ...... 

请求发出后requests会基于http头部对相应的编码做出有根据的推测当你访问r.text之时requests会使用其推测的文本编码。你可以找出requests使用了什么编码并且能够使用r.coding属性来改变它。

>>> r.content '<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> ...... 以二进制的方式打开服务器并返回数据。 

post请求

requests发送post请求通常你会想要发送一些编码为表单的数据——非常像一个html表单。要实现这个只需要简单地传递一个字典给data参数。你的数据字典在发出请求时会自动编码为表单形式。

>>> import requests >>> payload = {"key1":"value1","key2":"value2"} >>> r = requests.post("http://httpbin.org/post") >>> r1 = requests.post("http://httpbin.org/post", data=payload) 

看看效果

image.png

http头部

>>> r.headers['content-type'] 'application/json' 

注意在引号里面的内容不区分大小写'CONTENT-TYPE'也可以。

还能够自定义头部

>>> r.headers['content-type'] = 'adad' >>> r.headers['content-type'] 'adad' 

注意当定制头部的时候如果需要定制的项目有很多需要用到数据类型为字典。

    • *

备注

网上有一个更为详细叙述有关requests模块的网页可以参考http://requests-docs-cn.readthedocs.org/zh_CN/latest/index.html

原文链接:https://yq.aliyun.com/articles/687210
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章