Python自动化接口测试并导出测试结果
首先导入要用到的库
表格数据格式如下
![](https://img.haomeiwen.com/i14821840/f61caab9e680dd64.png)
import xlrd (用来读取表格数据)
import requests(用来进行网络请求)
import json
from xlutils.copy import copy
from datetime import datetime
import time
xlrd requests 需要在控制台进行pip install 安装 并导入
代码如下
timeIndex = 1 (请求次数)
file_path = input('请输入文件路径:') (输入表格路径: xxx/xxx/xxx.xls)
pathIndex = file_path.index('.') (获取.前面的路径)
save_path = file_path[0:pathIndex] + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + file_path[pathIndex: len(file_path)](输出表格,输出位置为输入表格同文件夹,名字为原表格名称+ 运行时间)
file = xlrd.open_workbook(file_path)(打开表格)
print(file)
timeStick = input('请输入间隔时长:')(循环间隔市场 单位 S)
write_data = copy(file)
table = file.sheets()[0](委屈表格中的sheets)
print("ssss", table.nrows)
print(file)
sheet = write_data.get_sheet(0)(获取第一个sheet)
//运用for循环去读取表格每行的数据
def Indsfesx():
print(file)
for index in range(1,table.nrows):
# print(sheet.row_values(index))
reques = table.row_values(index) //读取每行的数据 类型为dictionary
print(reques)
print(reques[1])
requestType = reques[1] //取出请求类型
requsertCode = 200
parsms = json.loads(reques[3]) //取出参数
url = reques[2] //取出接口地址
if requestType == 'get':
print('get请求')
payload = {}
headers = {}
respond = requests.request("GET", url, params=parsms, headers=headers)
print(respond.json())
print(respond.status_code)
# requsertCode = respond.status_code
sheet.write(index, 6, respond.status_code) //将结果写入表格
if respond.status_code == 200 :
requestJson = respond.json()
print(type(requestJson))
sheet.write(index, 9, respond.text)
# requestDic = json.loads(requestJson)
sheet.write(index, 7, requestJson['code'])
if requestJson['code'] == 0:
sheet.write(index, 8, 'true')//将结果写入表格
else:
sheet.write(index, 8, 'fasle')//将结果写入表格
# sheet.write(i, 6, requsertCode)
# sheet.write(index, 9, respond.text)
else:
print('post请求')
response = requests.post(url, data=parsms, headers=headers)
print(response.json())
sheet.write(index, 9, response.text)
# print(respond.status_code)
sheet.write(index, 6, response.status_code)
if response.status_code == 200:
requestJson = response.json()
print(type(requestJson))
sheet.write(index, 7, requestJson['code'])
if requestJson['code'] == 0:
sheet.write(index, 8, 'true')
else:
sheet.write(index, 8, 'fasle')
else:
sheet.write(index, 8, 'fasle')
def timer(n):
bools = True
while bools:
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(n) // 计时器间隔设置
Indsfesx()
global timeIndex
timeIndex = timeIndex + 1
if timeIndex == 5:
bools = False
Indsfesx()
write_data.save(save_path) // 将table 写入新的文件
timer(int(timeStick))
运行效果 :
![](https://img.haomeiwen.com/i14821840/d58fb0d849be087f.png)
![](https://img.haomeiwen.com/i14821840/7b833edb2996320f.png)
网友评论