基于Python的接口自動化讀寫excel文件的方法
使用python進行接口測試時常常需要接口用例測試數(shù)據(jù)、斷言接口功能、驗證接口響應(yīng)狀態(tài)等,如果大量的接口測試用例腳本都將接口測試用例數(shù)據(jù)寫在腳本文件中,這樣寫出來整個接口測試用例腳本代碼將看起來很冗余和難以清晰的閱讀以及維護,試想如果所有的接口測試數(shù)據(jù)都寫在代碼中,接口參數(shù)或者測試數(shù)據(jù)需要修改,那不得每個代碼文件都要一一改動?。因此,這種不高效的模式不是我們想要的。所以,在自動化測試中就有個重要的思想:測試數(shù)據(jù)和測試腳本分離,也就是測試腳本只有一份,其中需要輸入數(shù)據(jù)的地方會用變量來代替,然后把測試輸入數(shù)據(jù)單獨放在一個文件中,這個存放測試輸入數(shù)據(jù)的文件,通常是表格的形式或者其他格式文件,如excel文件、json文件、xml文件、txt文本文件等等。在python進行接口自動化測試時,為了方便管理和存儲測試用例數(shù)據(jù),一般將測試數(shù)據(jù)編寫存儲在excel文件中,測試腳本通過讀取excel文件來實現(xiàn)測試數(shù)據(jù)加載,并運行得出測試用例數(shù)據(jù)執(zhí)行的結(jié)果,并回寫測試結(jié)果到excel文件中,這樣就實現(xiàn)了測試腳本和數(shù)據(jù)的分離。而python操作excel文件的讀寫,這里需要安裝并引入第三方模塊:xlrd和xlwt以及xlutils,xlrd為讀取excel模塊,xlwt為向excel寫數(shù)據(jù)的模塊,xlutils可以復(fù)制excel并修改excel中的數(shù)據(jù)。下面就具體介紹xlrd和xlwt操作excel文件提供的通用方法和技巧,以及xlutils如何復(fù)制和修改excel,達到操作excel讀寫的目的。
一、xlrd、xlwt以及xlutils安裝1.使用pip安裝
pip install xlrdpip install xlwtpip install xlutils
2.在PyCharm中安裝
直接檢索需要安裝的模塊名稱即可,如xlrd:
新建一個excel文件,文件名稱:excel_test.xlsx,文件編輯有兩個sheet表,內(nèi)容如下:
sheet1:
sheet2:
(1)打開excel文件,獲取excel的sheet名
編輯如下代碼:
import xlrdfile = xlrd.open_workbook('excel_test.xlsx')all_sheet = file.sheet_names() # 獲取所有的工作簿名sheet_name1 = file.sheet_names()[0] # 通過sheet下標獲取,第一個sheet下標為0sheet_name2 = file.sheet_by_index(0).name # 通過sheet索引獲取sheet名print(all_sheet)print(sheet_name1)print(sheet_name2)-----------------------------------------# 返回結(jié)果[’員工信息表’, ’api測試用例’]員工信息表員工信息表
(2)獲取sheet工作表頁的對象
代碼示例:
import xlrdfile = xlrd.open_workbook('excel_test.xlsx')sheet_name1 = file.sheet_names()[0]sheet1_obj = file.sheet_by_name(sheet_name1) # 通過sheet名獲取sheet對象sheet2_obj = file.sheet_by_index(1) # 通過sheet索引獲取sheet對象print(sheet1_obj)print(sheet2_obj)------------------------------------# 返回結(jié)果<xlrd.sheet.Sheet object at 0x0000000002AA09B0><xlrd.sheet.Sheet object at 0x0000000002AA0978>
(3)獲取sheet工作表的行、列數(shù),整行、整列數(shù)據(jù),具體的單元格數(shù)據(jù)
代碼示例:
import xlrdfile = xlrd.open_workbook('excel_test.xlsx')sheet = file.sheet_by_index(0) # 通過sheet索引獲取sheet對象nrows = sheet.nrows # 獲取行數(shù)ncols = sheet.ncols # 獲取列數(shù)nrows_data = sheet.row_values(1) # 獲取第二行數(shù)據(jù),返回的是列表ncols_data = sheet.col_values(0) # 獲取第一列數(shù)據(jù),返回的是列表cell = sheet.cell(1,2) # 獲取單元格數(shù)據(jù),如第二行,第三列數(shù)據(jù)print(nrows)print(ncols)print(nrows_data)print(ncols_data)print(cell)-------------------------------# 返回結(jié)果65[’王五’, ’男’, 32883.0, ’java開發(fā)工程師’, 233.0][’姓名’, ’王五’, ’李四’, ’張三’, ’小紅’, ’小明’]xldate:32883.0 # 這里日期數(shù)據(jù)直接返回成浮點數(shù)了
常見讀取excel不同數(shù)據(jù)類型的返回問題,如讀取日期格式的數(shù)據(jù)
一般使用sheet.cell(rowx,colx)方法獲取單元格數(shù)據(jù),單元格數(shù)據(jù)類型判斷可以使用如下代碼:
print(sheet.cell(1,2).ctype)------------# 返回日期數(shù)據(jù)的結(jié)果3
注:ctype : 0 empty,1 string, 2 number,3 date, 4 boolean, 5 error
讀取單元格日期數(shù)據(jù)為浮點數(shù)的處理方式:
代碼如下:
import xlrdfrom datetime import datefile = xlrd.open_workbook('excel_test.xlsx')sheet = file.sheet_by_index(0) # 通過sheet索引獲取sheet對象nrows_data = sheet.row_values(1) # 獲取第二行數(shù)據(jù),返回的是列表ncols_data = sheet.col_values(0) # 獲取第一列數(shù)據(jù),返回的是列表cell = sheet.cell(1,2) # 獲取單元格數(shù)據(jù),如第二行,第三列數(shù)據(jù),返回的是浮點數(shù)data_value = xlrd.xldate_as_tuple(sheet.cell_value(1,2) ,file.datemode) # xldate_as_tuple()方法得到日期數(shù)據(jù)年月日時分秒的值并返回為元組datatime2 = date(*data_value[:3]).strftime(’%Y/%m/%d’) # 截取元組中的前三位,即年月日的值傳給data,并進行時間格式化 print(cell)print(data_value)print(datatime2) -----------------------# 返回結(jié)果xldate:32883.0(1990, 1, 10, 0, 0, 0)1990/01/10
因此在讀取excel單元格數(shù)據(jù),如遇到是日期格式的數(shù)據(jù),可以加上如下代碼判斷并處理:
if (sheet.cell(row,col).ctype == 3): date_value = xlrd.xldate_as_tuple(sheet.cell_value(row,col),file.datemode) date_tmp = date(*date_value[:3]).strftime(’%Y/%m/%d’)三、xlwt向excel文件寫入數(shù)據(jù)
xlwt一般用于向excel文件寫入數(shù)據(jù),簡單示例如下:
import xlwt workbook = xlwt.Workbook(encoding = ’utf-8’) # 創(chuàng)建工作簿sheet = workbook.add_sheet(’api_test’) # 添加一個sheetdata = sheet.write(0,0,’test’) # 向第一行第一列寫入數(shù)據(jù):testworkbook.save(’book.xlsx’) # 保存到book.xlsx中
運行完成后會在該py文件的同級目錄下生成一個book.xlsx的excel文件,并新增了api_test的sheet表名,第一行第一列寫入數(shù)據(jù):test
向excel寫入數(shù)據(jù)時,可以設(shè)置單元格長寬、單元格合并、寫入時間格式數(shù)據(jù)以及添加超鏈接等
代碼示例:
import xlwtimport datetimeworkbook = xlwt.Workbook(encoding = ’utf-8’) # 創(chuàng)建工作簿sheet = workbook.add_sheet(’api_test’) # 添加一個sheetdata = sheet.write(4,0,’test’) sheet.col(0).width = 5000 # 設(shè)置單元格寬度 style = xlwt.XFStyle() # 初始化表格樣式style.num_format_str = ’M/D/YY’ # 設(shè)置時間格式,如:M/D/YYsheet.write(5, 1, datetime.datetime.now(), style) # 寫入時間格式數(shù)據(jù) # 合并多列和和并多行# 表示合并的行數(shù)是:按行索引,從0行到第0行,按列索引從0列到第3列,合并后并寫入數(shù)據(jù):test1sheet.write_merge(0, 0, 0, 3, ’test1’)# 表示合并的行數(shù)是:按行索引,從1行到第2行,按列索引從0列到第3列,合并后并寫入數(shù)據(jù):test2sheet.write_merge(1, 2, 0, 3, ’test2’) # 向單元格添加超鏈接sheet.write(6, 0, xlwt.Formula(’HYPERLINK('https://www.baidu.com/';'baidu')’)) workbook.save(’book.xlsx’) # 保存到book.xlsx中
運行后輸出excel效果如下:
(1)拷貝excel表格
xlutils模塊下的copy可以復(fù)制拷貝excel文件,代碼示例:
import xlrdfrom xlutils.copy import copyexcel_file = xlrd.open_workbook('book.xlsx')new_file = copy(excel_file) # 拷貝文件對象new_file.save('book1.xlsx') # 保存為excel文件
運行以上代碼會在同級目錄下生成一個book1.xlsx的excel文件,該文件和book.xlsx一樣,只是文件名稱不一樣而已,也就是復(fù)制excel文件了
(2)修改excel文件內(nèi)容
除了copy為其他excel文件外,也可以直接copy文件修改后,保存為同名的文件,那修改的內(nèi)容將直接覆蓋原excel文件,達到修改的目的
示例:
import xlrdfrom xlutils.copy import copyexcel_file = xlrd.open_workbook('book.xlsx')new_file = copy(excel_file)sheet = new_file.get_sheet(0) # 獲取表格的第一個sheetsheet.write(0,1,'測試') # 第一行第二列寫入:測試sheet.write(1,1,'測試1') # 第二行第二列寫入:測試1new_file.save('book.xlsx')
運行后book.xlsx表會修改更新
五、封裝操作excel讀和寫的類通過上面介紹,基本具備使用xlrd、xlwt、xlutils模塊進行excel文件數(shù)據(jù)讀取和向excel文件中寫入數(shù)據(jù),在進行接口測試時,我們說到需要:測試數(shù)據(jù)和測試腳本分離,后續(xù)的接口測試用例數(shù)據(jù),我們統(tǒng)一寫入excel表格中,然后通過操作excel來讀取測試數(shù)據(jù)并將測試結(jié)果回填到excel中。因此,咱們需要對向excel讀取數(shù)據(jù)和向excel寫入數(shù)據(jù)的操作進行封裝。
我們操作上面的api測試用例這個sheet,封裝讀取excel數(shù)據(jù)的類,代碼示例:
from xlrd import open_workbookclass Readexcel(): def excel_data_list(self, filename, sheetname): ’’’ :param filename: excel文件名稱 :param sheetname: excel中表格sheet名稱 :return: data_list ’’’ data_list = [] wb = open_workbook(filename) # 打開excel sh = wb.sheet_by_name(sheetname) # 定位工作表 header = sh.row_values(0) # 獲取標題行的數(shù)據(jù) for i in range(1, sh.nrows): # 跳過標題行,從第二行開始獲取數(shù)據(jù) col_datas = dict(zip(header, sh.row_values(i))) # 將每一行的數(shù)據(jù),組裝成字典 data_list.append(col_datas) # 將字典添加到列表中 ,列表嵌套字典,每個元素就是一個字典 return data_list if __name__ == ’__main__’: Readexcel()
上面代碼封裝了讀取excel數(shù)據(jù)的類,將每一行數(shù)據(jù)讀取出來組裝成字典并添加到列表中
實例化運行:
data_list = Readexcel().excel_data_list(’excel_test.xlsx’,’api測試用例’) print(data_list)-----------------------# 返回結(jié)果[ {’module’: ’視頻安防’, ’url’: ’http://imp-t.tfgreenroad.com:18092/console_api/recep/tv/list’, ’id’: 1.0, ’params’: ’{ 'queryMsg':'','regionCode':'','devtypeCode':'','online':'','offset':'','limit':1,'type':''}’, ’method’: ’get’, ’actual_res’: ’’, ’data’: ’’, ’expect_res’: ’’, ’test_res’: ’’, ’case_name’: ’分頁查詢視頻安防設(shè)備列表’, ’files’: ’’}, {’module’: ’平臺管理’, ’url’: ’http://imp-t.tfgreenroad.com:18092/console_api/manage/appsys/info’, ’id’: 2.0, ’params’: ’’, ’method’: ’post’, ’actual_res’: ’’, ’data’: ’{'appName': 'hahh','appId': '34434343','appUrl': 'http://12306.com','appCode': '89','remark':''}’, ’expect_res’: ’{'code': 200,'errMsg': ''}’, ’test_res’: ’’, ’case_name’: ’應(yīng)用管理-單個應(yīng)用系統(tǒng)添加’, ’files’: ’’}, {’module’: ’平臺管理’, ’url’: ’http://imp-t.tfgreenroad.com:18092/console_api/manage/appsys/info/upappid/89’, ’id’: 3.0, ’params’: ’’, ’method’: ’put’, ’actual_res’: ’’, ’data’: ’{'appId': '3232327676888'}’, ’expect_res’: ’{'code': 200,'errMsg': ''}’, ’test_res’: ’’, ’case_name’: ’應(yīng)用管理-修改應(yīng)用appId’, ’files’: ’’}, {’module’: ’平臺管理’, ’url’: ’http://imp-t.tfgreenroad.com:18092/console_api/manage/devtype/list’, ’id’: 4.0, ’params’: ’{ 'queryMsg':'15002','offset':'','limit':''}’, ’method’: ’get’, ’actual_res’: ’’, ’data’: ’’, ’expect_res’: ’’, ’test_res’: ’’, ’case_name’: ’設(shè)備分類-分頁獲取設(shè)備類型’, ’files’: ’’}]
封裝向excel寫入數(shù)據(jù)的類,代碼示例:
from xlutils.copy import copyfrom xlrd import open_workbook class Write_excel(): def write_result(self, filename, row, col1,col2,actual_res, test_res,sheet_name): ’’’ :param filename: 文件名 :param row: 要寫回的行 :param col1: 要寫回的列 :param col2: 要寫回的列 :param actual_res: 實際結(jié)果 :param test_res: 測試結(jié)果 :pass/failed :param sheet_name:指定的sheet表索引 :return: ’’’ old_workbook = open_workbook(filename) # 將已存在的excel拷貝進新的excel new_workbook = copy(old_workbook) # 獲取sheet new_worksheet = new_workbook.get_sheet(sheet_name) # 第n個sheet,0表示第一個sheet # 寫入數(shù)據(jù) new_worksheet.write(row, col1, actual_res) new_worksheet.write(row, col2, test_res) # 保存 new_workbook.save('book.xlsx') if __name__ == ’__main__’: Write_excel()
這樣我們就完成了讀寫excel操作的封裝,后續(xù)接口測試數(shù)據(jù)的讀取和寫入就依靠這兩個類了。
到此這篇關(guān)于基于Python的接口自動化讀寫excel文件的文章就介紹到這了,更多相關(guān)Python接口自動化內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
