一、介绍
Requests是一个很实用的python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到,Requests是python语言的第三方库,专门用于发送HTTP请求。
二、前提
安装插件:pip install requests
三、get请求
GET无参请求:r = requests.get('http://www.baidu.com')
GET传参:payload = {'key1': 'value1', 'key2': 'value2', 'key3': None} r = requests.get('http://www.baidu.com ', params=payload)
四、post请求
类似python中的表单提交
import requests
class UseRequestClass():
def XWTTPostMethod(self):
params = {"type":"guonei","key":"4b72107de3a197b3bafd9adacf685790"}
r = requests.post("http://v.juhe.cn/toutiao/index",params=params)
print(r.status_code)
return r.status_code</pre>
五、Requests响应
r.status_code 响应状态码
r.heards 响应头
r.cookies 响应cookies
r.text 响应文本
r. encoding 当前编码
r. content 以字节形式(二进制)返回</pre>
六、Rquest扩充
1.添加等待时间
requests.get(url,timeout=1) #超过等待时间则报错
2.添加请求头信息
requests.get(url,headers=headers) #设置请求头
3.添加文件
requests.post(url, files=files) #添加文件</pre>
七、requests + pytest + allure
-
主要流程:
读取文件中的数据
requests拿到数据请求接口返回状态码
通过断言验证返回状态码和200对比
生成allure的测试报告</pre> -
读取csv文件流程
存储数据(csv):通过excel另存为csv即可
-
读取数据(readDemo):
import csv
class ReadCsv():
def readCsv(self):
item = []
rr = csv.reader(open("../dataDemo/123.csv"))
for csv_i in rr:
item.append(csv_i)
item =item [1:]
return item</pre> -
requests请求接口返回状态码
import requests
from readDataDemo.readcsv import ReadCsv
r = ReadCsv()
ee = r.readCsv()print(ee)
class RequestCsv():
def requestsCsv(self):
item = []
for csv_i in ee:
if csv_i[2] =="get":
rr = requests.get(csv_i[0],params=csv_i[1])
item.append(rr.status_code)
else:
rr = requests.post(csv_i[0],data=csv_i[1])
item.append(rr.status_code)
return item</pre> pytest断言设置并结合allure生成测试报告
import pytest,os,allure
from RequestsTest.TestCase.CsvRequCase import GetStausCodeg = GetStausCode() gg = g.getstauscode() class TestCsvCase: def testCsvcase(self): for code in gg: assert code == 200 pytest.main(['--alluredir', 'report/result', 'CsvCase.py']) split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean' os.system(split)</pre>
-
读取excle文件流程
存储数据(xlsx)
-
读取数据(readDemo)
安装openpyxl:
pip install openpyxl
from openpyxl import load_workbook
class ReadXcel:
def readxcel(self):
workbook = load_workbook('F:\ATsxt\python文档\python基础\RequestsTest\readData\aa.xlsx')sheet = workbook['Sheet1']
print(sheet.max_row)
print(sheet.max_column)
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</pre> -
request请求接口返回状态码
import requests
class UseRequestClass:
def XwtMethod(self):
params = {'stage_id':1,'limit':2}
r=requests.post('https://www.qubaobei.com/ios/cf/dish_list.php',data=params)
print(r.json(),r.status_code)u = UseRequestClass()
u.XwtMethod()</pre> pytest断言设置并结合allure生成测试报告