requests库的使用
requests是python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢?官方文档中是这样说明的:
“python的标准库urllib2提供了大部分需要的HTTP功能,但是API太逆天了,一个简单的功能就需要一大堆代码。”
简而言之,requests库就是简单易用。
使用:
1. 安装
https://pypi.python.org/pypi/requests
api:http://cn.python-requests.org/zh_CN/latest/
pip install requests
2.import requests
3.发送请求
3.1 requests.get(‘http://www.baidu.com‘)
配置url参数
params 关键字参数,以一个字典来提供这些参数
payload = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
requests.get(“http://httpbin.org/get“, params=payload)
3.2 requests.post(url)
3.2.1表单提交
data传入字典
payload = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
requests.post(“http://httpbin.org/post“, data=payload)
3.2.2 x-www-form-urlencoded形式
headers增加配置 Content-Type:application/x-www-form-urlencoded
data传入字典
3.2.3raw(文本)提交 字符串形式\xml形式
方式一:普通字符串(xml字符串)
payload = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" >'
r = requests.post(url, data=payload)
方式二:字典转字符串
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
json形式
payload = {'some': 'data'}
r = requests.post(url, json=payload)
3.2.4文件格式
files ={"file1":open("report.xls","rb"),"file2":...}
requests.post(url,file=files)
3.3定制请求头:
headers 字典
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
requests.get(url, headers=headers)
3.4添加Cookie
cookies 字典
cookies = dict(cookies_are='working')
cookies ={'cookies_are':'working'}
requests.get(url, cookies=cookies)
3.5超时**
timeout 仅对连接过程有效,与响应体的下载无关
超时则抛出requests.exceptions.Timeout
requests.get('http://github.com', timeout=0.001)
4、接受请求
resquest的get和post方法返回值都是response对象,其存储了服务器响应的内容。
响应状态码:
response.status_code
response.raise_for_status()
#失败请求(非200响应)抛出异常
响应头:
response.headers--字典
响应的cookie:
response.cookies--字典
响应体:response.text
–内容编码格式问题:
Requests 会基于 HTTP 响应头对响应的编码作出有根据的推测
response.encoding()
指定编码格式,之后再调用response.text显示的编码格式就是设置后的
响应中的字节内容(二进制):response.content
解析响应:
response.json 转换为字典
5、高级应用
Prepared Request
s = Session()
req = Request('GET', url,
data=data
headers=headers
)
prepped = s.prepare_request(req)
resp = s.send(prepped,
stream=stream,
verify=verify,
proxies=proxies,
cert=cert,
timeout=timeout
)
SSL证书验证
verify =False
例子:get 方法
#coding=UTF-8
import requests
import unittest
class getProduct(unittest.TestCase):
def test_getProduct(self):
para = {"user_id":"1"}
respones = requests.get("http://101.200.42.234:8116/v1/get/product",params=para)
print respones.text
# {"code":"0","msg":"","data":{"trade":[{"user_id":1,"product_id":1,"product_name":"电脑"},{"user_id":1,"product_id":2,"product_name":"电脑"},....]}}
# code = 0 ;商品数不为0
code = respones.json()["code"]
if code == "0":
data_a = respones.json()["data"]["trade"]
count = len(data_a)
if count>0:
print u"查询商品正确,共查询到:"+str(count)+u"个商品"
else:
print u"未查询到商品"
else:
print u"查询商品接口返回错误"
post方法
#coding=UTF-8
import requests
import unittest
class addProduct(unittest.TestCase):
def test_addProduct(self):
para ={"user_id":"1","product_name":"wanju"}
response = requests.post("http://101.200.42.234:8116/v1/add/product",params=para)
# print response.text
# {"code":"0","msg":"添加商品成功!","data":null}
code = response.json()["code"]
if code == "0":
print u"添加商品成功"
else:
print u"添加商品失败"
引入测试报告run.py
#coding=UTF-8
import unittest
# 测试报告类
import HTMLTestRunnerCN
#run.py跑全部用例文件
# 仍然引入unittest类
if __name__ == '__main__':
discover = unittest.defaultTestLoader.discover("./","*.py")
fp =open("./index.html","wb")
HTMLTestRunnerCN.HTMLTestRunner(stream=fp,title=u"接口自动化报告",description="111").run(discover)
fp.close()