目录:导读
一、requests库
Requests is an elegant and simple HTTP library for Python, built for human beings.
Requests库就是一个使用Python语言发送HTTP请求的一个类库。
github地址:https://github.com/psf/requests
中文地址:https://2.python-requests.org/zh_CN/latest/user/quickstart.html
二、发送基本请求
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)
二、参数传递
import requests
url = "http://httpbin.org"
param_data = {"name":"shiyan","password":"123456789"}
#get请求传递参数
r = requests.get(url+"/get",params=param_data)
print(r.url)
print(r.status_code)
param_data = {"name":"wangzhi","password":"20190001"}
#post请求传递参数
r = requests.post(url+"/post",data=param_data)
print(r.text)
三、请求头设置
import requests
url = "http://httpbin.org"
header = {"token":"201909011313"}
r = requests.get(url+"/get",headers=header)
print(r.text)
案例:访问知乎首页
import requests
url = "https://www.baidu.com/"
r = requests.get(url)
cookies = r.cookies
print(cookies)
for key,value in cookies.items():
print(key+":"+value)
四、cookies设置
import requests
url = "http://httpbin.org"
cookie = {"username":"shiyan"}
r = requests.get(url+"/get",cookies=cookie)
print(r.text)
五、超时设置
import requests
url = "http://httpbin.org"
r = requests.get(url+"/get",timeout=5)
print(r.text)
六、上传文件
import requests
#登录
loginUrl = "http://testapp.airspace.cn/api/passport/app/loginByPwd"
#loginName: 15201438478, password: 123456a, deviceVersion: PCT-AL10, deviceOsVersion: 9, appVersion: 1.1.6
loginParam = {"loginName":"15201438478","password":"123456a","deviceVersion":"PCT-AL10","deviceOsVersion":"9","appVersion":"1.1.6"}
r = requests.post(loginUrl,params=loginParam)
print(r.json())
loginToken = r.json()["data"]["loginToken"]
print(loginToken)
#图片上传
uploadImageUrl = "http://testapp.airspace.cn/api/image/upload"
headers = {"Token":loginToken}
files = {'image': open('upload.png', 'rb')}
r = requests.post(uploadImageUrl,files=files,headers=headers)
print(r.json())
七、会话对象
import requests
url = "http://httpbin.org"
#设置cookie
r = requests.get(url+"/cookies/set/user/shiyan")
print(r.text)
#获取cookie
r = requests.get(url+"/cookies")
print(r.text)
结果
import requests
url = "http://httpbin.org"
s = requests.session()
#设置cookie
r = s.get(url+"/cookies/set/user/shiyan")
print(r.text)
#获取cookie
r = s.get(url+"/cookies")
print(r.text)
结果
八、ssl验证
import requests
url = "https://www.12306.cn"
r = requests.get(url,verify=False)
print(r.text)
通过设置verify=False可以关闭ssl验证。
九、代理设置
import requests
url = "http://httpbin.org"
proxies = {"http":"http://111.231.140.109:8888"}
r = requests.get(url+"/get",proxies=proxies)
print(r.text)
结果
通过结果我们发现,通过代理发送请求后,服务器端收到的origin这个客户端地址就是我们设置的代理地址,客户端设置代理后,可以通过代理发送请求,防止请求接口次数过多时,服务器把客户端对应的ip地址添加到黑名单中。
十、身份认证
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
url = "http://httpbin.org"
#basic-auth认证
r = requests.get(url+"/basic-auth/shiyan/8888",auth=HTTPBasicAuth("shiyan","8888"))
print(r.text)
#digest-auth认证
r = requests.get(url+"/digest-auth/auth/shiyan/8888",auth=HTTPDigestAuth("shiyan","8888"))
print(r.text)
十一、实战 天气api
免费天气接口地址:https://www.sojson.com/api/weather.html
import requests
url = "http://t.weather.sojson.com/api/weather/city/"
cityId = "101030100"
r = requests.get(url+cityId)
response = r.json()
print(response["cityInfo"]["city"])
print(response["data"]["forecast"][0]["ymd"])
十二、unittest 实战天气api
import unittest
import requests
class WeatherTest(unittest.TestCase):
#开始
def setUp(self):
print("接口测试开始")
self.baseUrl = "http://t.weather.sojson.com/api/weather/city/"
#接口正常测试
def test_weather_tianjin(self):
self.url = self.baseUrl +"101030100"
r = requests.get(self.url)
response = r.json()
self.assertEqual(response["status"],200)
self.assertEqual(response["cityInfo"]["city"],"天津市")
#接口参数错误
def test_weather_params_error(self):
self.url = self.baseUrl + "8888"
r = requests.get(self.url)
response = r.json()
self.assertEqual(response["status"],404)
self.assertEqual(response["message"],"Request resource not found.")
#接口参数不传
def test_weather_params_no(self):
self.url = self.baseUrl
r = requests.get(self.url)
response = r.json()
self.assertEqual(response["status"], 404)
self.assertEqual(response["message"], "Request resource not found.")
#结束
def tearDown(self):
print("接口测试结束")
十三、测试报告生成
1.编写run脚本:run.py
import unittest
from BSTestRunner import BSTestRunner
import time
#指定测试用例和测试报告的路径
test_dir = "."
report_dir = "./reports"
#加载测试用例
discover = unittest.defaultTestLoader.discover(test_dir,pattern="unittest_weather_api.py")
#定义报告的文件格式
now = time.strftime("%Y-%m-%d %H_%M_%S")
report_name = report_dir + "/" + now + "test_report.html"
#运行用例并生成报告
with open(report_name,"wb") as f:
runner = BSTestRunner(stream=f,title="Weather Api Test Report",description="China City Weather Test Report")
runner.run(discover)
2.执行脚本
案例图示如下:
3.生成接口测试报告
效果图示如下: