Python3 API 第三方库 requests 详解
|
Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP?测试需求。Requests 的哲学是以 PEP 20 的习语为中心开发的,所以它比 urllib 更加 Pythoner。更重要的一点是它支持 Python3 哦!
一、安装 Requests通过pip安装 pip install requests
或者,下载代码后安装: $ git clone git://github.com/kennethreitz/requests.git $ cd requests $ python setup.py install 再懒一点,通过IDE安装吧,如pycharm! 二、发送请求与传递参数先来一个简单的例子吧!让你了解下其威力:
import requests r = requests.get(url='http://www.itwhy.org') # 最基本的GET请求 print(r.status_code) 获取返回状态 r = requests.get(url=http://dict.baidu.com/s',params={wd':python'}) 带参数的GET请求 print(r.url) print(r.text) 打印解码后的返回数据
很简单吧!不但GET方法简单,其他方法都是统一的接口样式哦!
PS:以上的HTTP方法,对于WEB系统一般只支持 GET 和 POST,有一些还支持 HEAD 方法。 import requests requests.get(http://www.dict.baidu.com/s': '}) GET参数实例 requests.post(http://www.itwhy.org/wp-comments-post.PHPcomment测试POSTPOST参数实例 POST发送JSON数据: import requests import json r = requests.post(https://api.github.com/some/endpointsomedata'})) print(r.json())定制header: import json data = {'} headers = {content-typeapplication/json',User-AgentMozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} r = requests.post(headers) print(r.text)
三、Response对象 使用requests方法后,会返回一个response对象,其存储了服务器响应的内容,如上实例中已经提到的 r.text、r.status_code…… r = requests.get(') print(r.text,n{}n'.format(*'*79),r.encoding) r.encoding = GBK' '*79),r.encoding) 其他响应:
案例之一: import requests URL = http://ip.taobao.com/service/getIpInfo.PHP' 淘宝IP地址库API try: r = requests.get(URL,0); line-height:1.5!important">ip8.8.8.8'},timeout=1) r.raise_for_status() 如果响应状态码不是 200,就主动抛出异常 except requests.RequestException as e: print(e) else: result = r.json() print(type(result),result,sep=n') 四、上传文件使用 Requests 模块,上传文件也是如此简单的,文件的类型会自动进行处理: import requests url = http://127.0.0.1:5000/upload' files = {file': open(/home/lyb/sjzl.mpgrb')} files = {'file': ('report.jpg',open('/home/lyb/sjzl.mpg','rb'))} #显式的设置文件名 r = requests.post(url,files=files) 更加方便的是,你可以把字符串当着文件进行上传: ': (test.txtHello Requests.')} 必需显式的设置文件名 r = requests.post(url,sans-serif"> 五、身份验证基本身份认证(HTTP Basic Auth): from requests.auth import HTTPBasicAuth r = requests.get(https://httpbin.org/hidden-basic-auth/user/passwduserpasswd')) r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd',auth=('user','passwd')) # 简写 另一种非常流行的HTTP身份认证形式是摘要式身份认证,Requests对它的支持也是开箱即可用的:requests.get(URL,auth=HTTPDigestAuth(pass')) 六、Cookies与会话对象如果某个响应中包含一些Cookie,你可以快速访问它们: import requests r = requests.get(http://www.google.com.hk/print(r.cookies[NID']) print(tuple(r.cookies))要想发送你的cookies到服务器,可以使用 cookies 参数: http://httpbin.org/cookies' cookies = {testCookies_1Hello_Python3testCookies_2Hello_Requests'} 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。 r = requests.get(url,cookies=cookies) print(r.json()) 会话对象让你能够跨请求保持某些参数,最方便的是在同一个Session实例发出的所有请求之间保持cookies,且这些都是自动处理的,甚是方便。下面就来一个真正的实例,如下是快盘签到脚本: import requests headers = {Accepttext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Encodinggzip,deflate,compressAccept-Languageen-us;q=0.5,en;q=0.3Cache-Controlmax-age=0Connectionkeep-alive'} s = requests.Session() s.headers.update(headers) s.auth = ('superuser','123') s.get(https://www.kuaipan.cn/account_login.htm') _URL = http://www.kuaipan.cn/index.php' s.post(_URL,params={acaccountoplogin'},data={username****@foxmail.comuserpwd********isajaxyes'}) r = s.get(_URL,0); line-height:1.5!important">zonetaskdetail'}) print(r.json()) s.get(_URL,0); line-height:1.5!important">commonusersign'}) 七、超时与异常 timeout 仅对连接过程有效,与响应体的下载无关。 >>> requests.get(http://github.com) Traceback (most recent call last): File "<stdin>",line 1,in <module> requests.exceptions.Timeout: HTTPConnectionPool(host=github.com 所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException:ConnectionError、HTTPError、Timeout、TooManyRedirects。 |

