一、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"
r = requests.get(base_url+"/get")
print(r.status_code)
r = requests.post(base_url+'/post')
print(r.status_code)
r = requests.put(base_url+"/put")
print(r.status_code)
r = requests.delete(base_url+"/delete")
print(r.status_code)
二、参数传递
import requests
url = "http://httpbin.org"
param_data = {"name":"shiyan","password":"123456789"}
r = requests.get(url+"/get",params=param_data)
print(r.url)
print(r.status_code)
param_data = {"name":"wangzhi","password":"20190001"}
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"
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"
r = requests.get(url+"/cookies/set/user/shiyan")
print(r.text)
r = requests.get(url+"/cookies")
print(r.text)
结果
import requests
url = "http://httpbin.org"
s = requests.session()
r = s.get(url+"/cookies/set/user/shiyan")
print(r.text)
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"
r = requests.get(url+"/basic-auth/shiyan/8888",auth=HTTPBasicAuth("shiyan","8888"))
print(r.text)
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.生成接口测试报告 效果图示如下:
|