requests 测试demo http://httpbin.org/
使用 pip 安装命令如下: pip install requests 安装检测 打开 cmd 窗口,输入 python 然后导入 requests 如果安装成功没有任何提示 import requests
发送不同类型 HTTP 请求
import requests base_url='http://httpbin.org' #发送 GET 类型的请求 r=requests.get(base_url+'/get') print(r.status_code)
#发送 Post 类型请求 r=requests.post(base_url+'/post') print(r.status_code)
#发送 PUT 类型请求 r=requests.put(base_url+'/put') print(r.status_code)
#发送 Delete 类型请求 r=requests.delete(base_url+'/delete') print(r.status_code)
GET 传参
import requests base_url='http://httpbin.org' param_data={'user':'zxw','password':'666'} r=requests.get(base_url+'/get',params=param_data) print(r.url) print(r.status_code)
POST传参
form_data = {'user': 'zxw', 'passwd': '8888'} r=requests.post(base_url+'/post',data=form_data) print(r.text)
{ "args": {}, "data": "", "files": {}, "form": { "passwd": "8888", "user": "zxw" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Content-Length": "20", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.4" }, "json": null, "origin": "110.52.4.225", "url": "http://httpbin.org/post" }
header 请求头定制
form_data = {'user': 'zxw', 'passwd': '8888'} header={'user-agent':'Mozilla/5.0'} r=requests.post(base_url+'/post',data=form_data,headers=header)
print(r)
{ "args": {}, "data": "", "files": {}, "form": { "passwd": "8888", "user": "zxw" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Content-Length": "20", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "Mozilla/5.0" }, "json": null, "origin": "110.52.2.106", "url": "http://httpbin.org/post" }
设置成浏览器的请求头
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36' } r = requests.get("https://www.zhihu.com/explore",headers=headers) print(r.text)
给请求设置cookie
import requests cookie={'user':'51zxw'} r=requests.get(base_url+'/cookies',cookies=cookie) print(r.text)
运行结果: {"cookies":{"user":"51zxw"}}
请求百度,然后获取cookie
# 获取 cookie r=requests.get('http://www.baidu.com') print(type(r.cookies)) print(r.cookies) for key,value in r.cookies.items(): print(key+':'+value)
运行结果: <class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]> BDORZ:27315
下面案例故意设置一个很小的超时时间,为了来看一下超时后的一个响应处理,但是实际测试过程中不要设置这短。
r=requests.get(base_url+'/cookies',cookies=cookies,timeout=0.001) print(r.text)
上传文件接口
#上传文件 file={'file':open('zxw_logo.png','rb')} r=requests.post(base_url+'/post',files=file) print(r.text)
==========================================================================
会话(Session)
在接口测试过程中接口之间经常有依赖关系,比如下面这两个请求一个是设置 Cookie,另外一个是获取 cookie
#生成会话对象 s=requests.Session() #设置 Cookie r=s.get(base_url+'/cookies/set/user/51zxw') print(r.text) #获取 Cookie r=s.get(base_url+'/cookies') print(r.text)
{ "cookies": { "user": "51zxw" } } { "cookies": { "user": "51zxw" } }
SSL 证书验证
Requests 可以为 HTTPS 请求验证 SSL 证书,就像 web 浏览器一样。SSL 验证默认是开启的,如果证书验证 失败,Requests 会抛出 SSLError: 如果不想验证 SSL 则可以使用 verify 参数关闭验证 SSL。
r=requests.get('https://www.12306.cn') #关闭验证 SSL #r=requests.get('https://www.12306.cn',verify=False) print(r.text)
raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='www.12306.cn', port=443): Max retries exceeded with url: / (Caused by SSLError(CertificateError("hostname 'www.12306.cn' doesn't match either of 'webssl
代理设置
#代理设置 proxies={'http':'http://219.141.153.41:80'} r=requests.get(base_url+'/get',proxies=proxies) print(r.text)
{ "args": {}, "headers": { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en-US,en;q=0.5", "Cache-Control": "max-age=86400", "Connection": "close", "Host": "httpbin.org", "User-Agent": "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52" }, "origin": "219.141.153.41", "url": "http://httpbin.org/get" }
身份认证
下面案例主要验证了 2 种身份类型:BasicAuth 和 digestAuth
from requests.auth import HTTPBasicAuth from requests.auth import HTTPDigestAuth #身份认证-BasicAuth r=requests.get(base_url+'/basic-auth/51zxw/8888',auth=HTTPBasicAuth('51zxw','8888')) print(r.text) #身份认证——DigestAuth r=requests.get(base_url+'/digest-auth/auth/zxw/6666',auth=HTTPDigestAuth('zxw','6666')) print(r.text)
{"authenticated":true,"user":"51zxw"} {"authenticated":true,"user":"zxw"}
流式请求
有一些接口返回值比较特殊,不是单纯返回一个结果,而是多个结果,比如某个查询接口,返回值为排行榜前 10 的 商品信息。
import json r=requests.get(base_url+'/stream/10',stream=True) #如果响应内容没有设置编码,则默认设置为 utf-8 if r.encoding is None: r.encoding='utf-8'#对响应结果进行迭代处理 for line in r.iter_lines(decode_unicode=True): if line: data=json.loads(line) print(data['id']) 返回结果: 0 1 2 3 4 5 6 7 8 9