自动化测试Python处理Excel小技巧,你get了嘛

在这里插入图片描述

在自动化测试,尤其是接口自动化测试中,我们经常使用Excel做为数据驱动,那么如何快速的操作Excel呢?这里简单介绍几种常用的第三方库。

一.操作excel第三方模块库

xlrd
xlwt
xlutils
openpyxl

二.使用xlrd读取excel文件

1.安装

windows:pip install xlrd
mac:pip3 install xlrd

2.具体代码

import os
import xlrd
import xlwt

def read_excel():
    # 获取excel
    base_dir = os.path.dirname(os.path.abspath(__file__))
    testdata = base_dir + '/../testcases/testcases.xls'
    # 打开xls文件
    data = xlrd.open_workbook(testdata)
    # 打开第一张表
    table = data.sheets()[0]
    nrows = table.nrows # 获取表的行数
    for i in range(nrows):
        if i == 0:# 跳过首行,首行为title
            continue
        print (table.row_values(i))

if __name__ == '__main__':
    read_excel()

3.运行结果

[1.0, '登录成功获取token', 'SIT', 'https://test-mrjade.com/admin/token', 'post', '{\n"json":{"password":"1234","username":mrjade"}\n}', 200.0, 'json', '[["token","$.."]]', '', '']
[2.0, '注册', 'SIT', 'https://test-mrjade.com/admin/register', 'post', '{\n"json":{"password":"1234","username":mrjade"}\n}', 200.0, 'json', '', '', '']

4.注意:xlrd只能读取excel,不能进行其它操作,且xlrd只能操作后缀为.xls的文件,如果操作后缀为.xlsx的文件,则会抛出异常

Traceback (most recent call last):
  File "/Users/TesterRoad/Documents/python/ReadExcel.py", line 27, in <module>
    read_excel()
  File "/Users/TesterRoad/Documents/python/ReadExcel.py", line 17, in read_excel
    data = xlrd.open_workbook(testdata)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/xlrd/__init__.py", line 170, in open_workbook
    raise XLRDError(FILE_FORMAT_DESCRIPTIONS[file_format]+'; not supported')
xlrd.biffh.XLRDError: Excel xlsx file; not supported

三.使用xlwt写入文件

1.安装

windows:pip install xlwt
mac:pip3 install xlwt

2.具体代码

def write_excel():
    wbk = xlwt.Workbook()
    # sheet表取名为order
    sheet = wbk.add_sheet('order')
    # 将每行数据放到一个元组中,将所有数据放到一个list中,写入excel
    testdata = [('id', 'title', 'env', 'url', 'method', 'request_data', 'status_code', 'res_type', 'extract', 'expect_data', 'sql'),('1', '登录成功获取token', 'SIT', 'https://test-mrjade.com/admin/token', 'post', '{\n"json":{"password":"1234","username":mrjade"}\n}', '200', 'json', '[["token","$.."]]'),('2', '注册', 'SIT', 'https://test-mrjade.com/admin/register', 'post', '{\n"json":{"password":"1234","username":mrjade"}\n}', '200', 'json')]
    # 遍历数组(excel行数据)
    for i in range(len(testdata)):
        print(testdata[i])
        # 遍历数组中的元组(行单元格数据)
        for j in range(len(testdata[i])):
            # 将数据写入excel,i表示第几行,j表示单元格
            sheet.write(i,j,testdata[i][j])
    # excel保存目录
    base_dir = os.path.dirname(os.path.abspath(__file__))
    save_testdata = base_dir + '/../testcases/testcases1.xls'
    # 保存
    wbk.save(save_testdata)

if __name__ == '__main__':
    write_excel()

3.运行结果在这里插入图片描述
4.需要注意的是xlwt是不能对excel中数据做修改操作的

四.使用xlutils修改excel数据

1.安装

windows:pip install xlutils
mac:pip3 install xlutils

2.具体代码

from xlutils.copy import copy
def edit_excel():
    # excel目录
    base_dir = os.path.dirname(os.path.abspath(__file__))
    save_testdata = base_dir + '/../testcases/testcases1.xls'
    # 打开excel
    workbook = xlrd.open_workbook(save_testdata)
    workbooknew = copy(workbook)
    ws = workbooknew.get_sheet(0)
    # 将第3行,第2列修改为注册成功
    ws.write(2, 1, '注册成功')
    # 保存修改后的excel
    workbooknew.save(save_testdata)
if __name__ == '__main__':
    edit_excel()

3.运行结果在这里插入图片描述
五.使用openpyxl修改excel数据(墙列推荐)

1.安装

windows:pip install openpyxl
mac:pip3 install openpyxl

2.具体代码

from openpyxl import load_workbook

def useopenpyxl_edit_excel():
    # excel目录
    base_dir = os.path.dirname(os.path.abspath(__file__))
    save_testdata = base_dir + '/../testcases/testcases.xlsx'
    # 打开excel
    workbook = load_workbook(save_testdata)
    # 获取sheet
    ws = workbook["member"]
    print(ws)
    # 创建一个列表容器存放数据
    data = []
    # 将所有行数据转换成list
    row_list = list(ws.rows)
    print("row_list:",row_list)
    # 获取表头
    excel_title = row_list[0]
    print("获取表头:",excel_title)
    title_list = []
    i = 1;
    for row in excel_title:
        print("第1行第"+str(i)+"个单元格数据:",row.value)
        # 将获取的表头数据存放在list中
        title_list.append(row.value)
        i += 1
    print("表头字段:",title_list)
    # 5. 获取其他数据
    for row in row_list[1:]:
        cell_list = []
        # 获取每一个行数据
        for cell in row:
            # print(cell.value)
            cell_list.append(cell.value)
        print("除表头外的数据:",cell_list)
        # 将表头与这一行数据打包,转换成字典
        print(dict(zip(title_list,cell_list)))

if __name__ == '__main__':
    useopenpyxl_edit_excel()

3.运行结果

<Worksheet "member">
row_list: [(<Cell 'member'.A1>, <Cell 'member'.B1>, <Cell 'member'.C1>, <Cell 'member'.D1>, <Cell 'member'.E1>, <Cell 'member'.F1>, <Cell 'member'.G1>, <Cell 'member'.H1>, <Cell 'member'.I1>, <Cell 'member'.J1>, <Cell 'member'.K1>), (<Cell 'member'.A2>, <Cell 'member'.B2>, <Cell 'member'.C2>, <Cell 'member'.D2>, <Cell 'member'.E2>, <Cell 'member'.F2>, <Cell 'member'.G2>, <Cell 'member'.H2>, <Cell 'member'.I2>, <Cell 'member'.J2>, <Cell 'member'.K2>), (<Cell 'member'.A3>, <Cell 'member'.B3>, <Cell 'member'.C3>, <Cell 'member'.D3>, <Cell 'member'.E3>, <Cell 'member'.F3>, <Cell 'member'.G3>, <Cell 'member'.H3>, <Cell 'member'.I3>, <Cell 'member'.J3>, <Cell 'member'.K3>)]
获取表头: (<Cell 'member'.A1>, <Cell 'member'.B1>, <Cell 'member'.C1>, <Cell 'member'.D1>, <Cell 'member'.E1>, <Cell 'member'.F1>, <Cell 'member'.G1>, <Cell 'member'.H1>, <Cell 'member'.I1>, <Cell 'member'.J1>, <Cell 'member'.K1>)1行第1个单元格数据: id
第1行第2个单元格数据: title
第1行第3个单元格数据: env
第1行第4个单元格数据: url
第1行第5个单元格数据: method
第1行第6个单元格数据: request_data
第1行第7个单元格数据: status_code
第1行第8个单元格数据: res_type
第1行第9个单元格数据: extract
第1行第10个单元格数据: expect_data
第1行第11个单元格数据: sql
  
表头字段: ['id', 'title', 'env', 'url', 'method', 'request_data', 'status_code', 'res_type', 'extract', 'expect_data', 'sql']

除表头外的数据: [1, '登录成功获取token', 'SIT', 'https://test-mrjade.com/admin/token', 'post', '{\n"json":{"password":"1234","username":mrjade"}\n}', 200, 'json', '[["token","$.."]]', 200, None]

字典:{'id': 1, 'title': '登录成功获取token', 'env': 'SIT', 'url': 'https://test-mrjade.com/admin/token', 'method': 'post', 'request_data': '{\n"json":{"password":"1234","username":mrjade"}\n}', 'status_code': 200, 'res_type': 'json', 'extract': '[["token","$.."]]', 'expect_data': 200, 'sql': None}

除表头外的数据: [2, '注册', 'SIT', 'https://test-mrjade.com/admin/register', 'post', '{\n"json":{"password":"1234","username":mrjade"}\n}', 200, 'json', None, 200, None]

4.注意:openpyxl只能操作后缀为.xlsx的文件,如果操作后缀为.xls的文件,则会抛出异常

Traceback (most recent call last):
  File "/Users/TesterRoad/Documents/python/ReadExcel.py", line 83, in <module>
    useopenpyxl_edit_excel()
  File "/Users/TesterRoad/Documents/python/ReadExcel.py", line 66, in useopenpyxl_edit_excel
    workbook = load_workbook(save_testdata)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/openpyxl/reader/excel.py", line 315, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/openpyxl/reader/excel.py", line 124, in __init__
    self.archive = _validate_archive(fn)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/openpyxl/reader/excel.py", line 94, in _validate_archive
    raise InvalidFileException(msg)
openpyxl.utils.exceptions.InvalidFileException: openpyxl does not support the old .xls file format, please use xlrd to read this file, or convert it to the more recent .xlsx file format.

Process finished with exit code 1

最后我也整理了一些软件测试学习资料,对于学软件测试的小伙伴来说应该会很有帮助。有需要资料的朋友可以关注公众号:软件测试小dao,免费获取!包括,软件学习路线图,50多天的上课视频、16个突击实战项目,80余个软件测试用软件,37份测试文档,70个软件测试相关问题,40篇测试经验级文章,上千份测试真题分享,还有2021软件测试面试宝典,还有软件测试求职的各类精选简历,希望对大家有所帮助……

学习不要孤军奋战,最好是能抱团取暖,相互成就一起成长,群众效应的效果是非常强大的,大家一起学习,一起打卡,会更有学习动力,也更能坚持下去。

敲字不易,如果此文章对你有帮助的话,点个赞收个藏,给作者一个鼓励。也方便你下次能够快速查找。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python3读取Excel进行自动化测试是一种常见的测试方法。Python提供了许多库来处理Excel文件,其中最常用的是openpyxl库。通过openpyxl库,我们可以轻松地读取Excel文件并提取其中的数据,然后利用这些数据进行自动化测试。 首先,我们需要安装openpyxl库。可以使用pip命令在命令行中安装该库: ``` pip install openpyxl ``` 接下来,我们可以使用openpyxl库中的load_workbook函数打开Excel文件: ```python from openpyxl import load_workbook workbook = load_workbook('test_data.xlsx') ``` 在这里,‘test_data.xlsx’是我们要读取的Excel文件名。 一旦打开Excel文件,我们就可以通过工作簿对象来访问不同的工作表。可以使用get_sheet_names方法来获取所有工作表的名称,并选择要读取的工作表: ```python worksheet = workbook['Sheet1'] ``` 接下来,我们可以使用iter_rows方法迭代读取工作表中的每一行数据,并将其存储到一个列表中: ```python data = [] for row in worksheet.iter_rows(): row_data = [] for cell in row: row_data.append(cell.value) data.append(row_data) ``` 读取完Excel中的数据后,我们可以根据测试需求进行自动化测试。可以使用该数据来驱动测试工具或框架,执行不同的测试用例,评估测试结果,并生成报告。 利用Python3读取Excel进行自动化测试,可以大大减少测试过程中的人工操作和重复劳动,提高测试效率和准确性。例如,我们可以使用循环结构和条件语句来自动化执行各种测试用例,并使用断言语句进行结果验证。 总结起来,Python3读取Excel进行自动化测试是一种强大而灵活的测试方法,可以根据实际需求进行定制化的测试,并提高测试效率和质量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值