requests是一个很实用的python http客户端库,编写爬虫和测试服务器响应数据时经常会用到,requests是python语言的第三方的库,专门用于发送http请求
pip install requests
无参请求
r = requests.get('http://www.baidu.com')
get传参
payload = {'key1': 'value1', 'key2': 'value2', 'key3': None}r = requests.get('http://www.baidu.com ', params=payload)
案例:
代码
- import requests
- class UseRequestClass():
- #get传参的第一种方式
- def XWTTMethod(self):
- r = requests.get("http://v.juhe.cn/toutiao/index?type=guonei&key=4b72107de3a197b3bafd9adacf685790")
- print(r.text,r.json(),r.status_code)
- #get传参的第二种方式
- def XWTTMethod(self):
- params = {"type":"guonei","key":"4b72107de3a197b3bafd9adacf685790"}
- r = requests.get("http://v.juhe.cn/toutiao/index",params=params)
- print(r.text)
- import requests
- class UseRequestClass():
- def WeatherMethod(self):
- params={"city":"北京","key":"0e56bbb0ed90af8c99589c267389d361"}
- r=requests.get("http://apis.juhe.cn/simpleWeather/query",params=params)
- print(r.json())
- if __name__ == '__main__':
- u=UseRequestClass()
- u.WeatherMethod()
r.status_code 响应状态码
r.heards 响应头
r.cookies 响应cookies
r.text 响应文本
r.json() 响应的字典类型数据
r.encoding 当前编码
r.content 以字节形式(二进制)返回
最常用的是根据响应状态码判断接口是否连通,经常用于做接口中断言判断
1:添加等待时间
request.get(url.timeout=1) #超过等待时间则报错
2:添加请求头信息
requests.get(url,headers=headers) #设置请求头
3:添加文件
requests.post(url,files=files) #添加文件
文件传输
url ="http://httpbin.org/post"
files={"file":open("report.xls","rb")}
r=requests.post(url,files=files)
读取文件中的数据
requests拿到数据请求接口返回状态码
通过断言验证返回的数据和逾期结果
生成allure的测试报告
datademo(存放数据)>>readDemo(读取数据)>>restDemo(发送请求生成报告)
代码展示
- import csv
- class ReadCsv():
- def read_csv(self):
- file=csv.reader(open("../dataDemo/data.csv"))
- item=[]
- for i in file:
- item.append(i)
- item=item[1::]
- return item
- r=ReadCsv()
- print(r.read_csv())
代码展示
- import unittest,requests
- from boke.readDemo.readcsv import ReadCsv
- r=ReadCsv()
- a=r.read_csv()
- class APIclass(unittest.TestCase):
- def test001(self):
- for i in a:
- cs=eval(i[1])
- if i[2]=="get":
- object=requests.get(url=i[0],params=cs)
- self.assertEqual(object.json()["error_code"],int(i[3])) #断言验证
- else:
- object=requests.post(url=i[0],data=cs)
- self.assertEqual(object.json()["error_code"],int(i[3]))
- if __name__ == '__main__':
- unittest.main()
- import unittest
- from boke.common.HTMLTestRunner import HTMLTestRunner
- from boke.testDemo.testcsv import APIclass
- class HtmlClass():
- def send_html(self):
- suite=unittest.TestSuite()
- list=["test001"]
- for i in list:
- suite.addTest(APIclass(i))
- with open("../report.html","wb") as f:
- HTMLTestRunner(
- stream=f,
- verbosity=1,
- title="接口自动化测试",
- description=None
- ).run(suite)
-
- h=HtmlClass()
- h.send_html()
代码展示
- from openpyxl import load_workbook
- class ReadExcle():
- def read_excel(self):
- #打开表
- wb = load_workbook("../dataDemo/test001.xlsx")
- sheet =wb["Sheet1"]
- test_data=[]#把所有行的数据放在列表中
- for i in range(2,sheet.max_row+1): #控制行数
- sub_data={}#把每行的数据放在字典中
- for j in range(1,sheet.max_column+1): #控制列数
- sub_data[sheet.cell(1,j).value]=sheet.cell(i,j).value
- test_data.append(sub_data) #拼接每行单元格数据
- return test_data
- if __name__ == '__main__':
- r=ReadExcle()
- print(r.read_excel())
- import requests,pytest,os
- from boke.readDemo.readxlsx import ReadExcle
- r=ReadExcle()
- aa=r.read_excel()
- class TestXlsxClass():
- def test001(self):
- for i in aa:
- cs=eval(i["params"])
- if i["method"]=="get":
- object=requests.get(url=i["url"],params=cs)
- assert object.json()["error_code"]==i["dy"]
- # print('resultobject.json()["error_code"]', type(object.json()["error_code"]))
- # print('i["dy"]', type(i["dy"]))
- else:
- object=requests.post(url=i["url"],data=cs)
- assert object.json()["error_code"]==i["dy"]
- if __name__ == '__main__':
- # 生成测试报告json
- pytest.main(["-s", "-q", '--alluredir', 'report/result', 'testxlsx.py'])
- # 将测试报告转为html格式
- split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean'
- os.system('cd D:\install\python/python\Test_allure\Test/test\report')
- os.system(split)
( ̄▽ ̄)~*------ ٩(๑❛ᴗ❛๑)۶谢谢阅读!!!!!!!!!!!!!