基于Python的接口自動化讀寫excel文件的方法
引言
使用python進(jìn)行接口測試時常常需要接口用例測試數(shù)據(jù)、斷言接口功能、驗證接口響應(yīng)狀態(tài)等,如果大量的接口測試用例腳本都將接口測試用例數(shù)據(jù)寫在腳本文件中,這樣寫出來整個接口測試用例腳本代碼將看起來很冗余和難以清晰的閱讀以及維護(hù),試想如果所有的接口測試數(shù)據(jù)都寫在代碼中,接口參數(shù)或者測試數(shù)據(jù)需要修改,那不得每個代碼文件都要一一改動?。因此,這種不高效的模式不是我們想要的。所以,在自動化測試中就有個重要的思想:測試數(shù)據(jù)和測試腳本分離,也就是測試腳本只有一份,其中需要輸入數(shù)據(jù)的地方會用變量來代替,然后把測試輸入數(shù)據(jù)單獨放在一個文件中,這個存放測試輸入數(shù)據(jù)的文件,通常是表格的形式或者其他格式文件,如excel文件、json文件、xml文件、txt文本文件等等。在python進(jìn)行接口自動化測試時,為了方便管理和存儲測試用例數(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,達(dá)到操作excel讀寫的目的。
一、xlrd、xlwt以及xlutils安裝
1.使用pip安裝
pip install xlrd pip install xlwt pip install xlutils
2.在PyCharm中安裝
直接檢索需要安裝的模塊名稱即可,如xlrd:
二、xlrd操作excel文件的數(shù)據(jù)讀取
新建一個excel文件,文件名稱:excel_test.xlsx,文件編輯有兩個sheet表,內(nèi)容如下:
sheet1:
sheet2:
(1)打開excel文件,獲取excel的sheet名
編輯如下代碼:
import xlrd file = xlrd.open_workbook("excel_test.xlsx") all_sheet = file.sheet_names() # 獲取所有的工作簿名 sheet_name1 = file.sheet_names()[0] # 通過sheet下標(biāo)獲取,第一個sheet下標(biāo)為0 sheet_name2 = file.sheet_by_index(0).name # 通過sheet索引獲取sheet名 print(all_sheet) print(sheet_name1) print(sheet_name2) ----------------------------------------- # 返回結(jié)果 ['員工信息表', 'api測試用例'] 員工信息表 員工信息表
(2)獲取sheet工作表頁的對象
代碼示例:
import xlrd file = 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 xlrd file = 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é)果 6 5 ['王五', '男', 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 xlrd from datetime import date file = 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,并進(jìn)行時間格式化 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') # 添加一個sheet data = sheet.write(0,0,'test') # 向第一行第一列寫入數(shù)據(jù):test workbook.save('book.xlsx') # 保存到book.xlsx中
運行完成后會在該py文件的同級目錄下生成一個book.xlsx的excel文件,并新增了api_test的sheet表名,第一行第一列寫入數(shù)據(jù):test
向excel寫入數(shù)據(jù)時,可以設(shè)置單元格長寬、單元格合并、寫入時間格式數(shù)據(jù)以及添加超鏈接等
代碼示例:
import xlwt import datetime workbook = xlwt.Workbook(encoding = 'utf-8') # 創(chuàng)建工作簿 sheet = workbook.add_sheet('api_test') # 添加一個sheet data = sheet.write(4,0,'test') sheet.col(0).width = 5000 # 設(shè)置單元格寬度 style = xlwt.XFStyle() # 初始化表格樣式 style.num_format_str = 'M/D/YY' # 設(shè)置時間格式,如:M/D/YY sheet.write(5, 1, datetime.datetime.now(), style) # 寫入時間格式數(shù)據(jù) # 合并多列和和并多行 # 表示合并的行數(shù)是:按行索引,從0行到第0行,按列索引從0列到第3列,合并后并寫入數(shù)據(jù):test1 sheet.write_merge(0, 0, 0, 3, 'test1') # 表示合并的行數(shù)是:按行索引,從1行到第2行,按列索引從0列到第3列,合并后并寫入數(shù)據(jù):test2 sheet.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效果如下:
四、xlutils操作excel文件
(1)拷貝excel表格
xlutils模塊下的copy可以復(fù)制拷貝excel文件,代碼示例:
import xlrd from xlutils.copy import copy excel_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文件,達(dá)到修改的目的
示例:
import xlrd from xlutils.copy import copy excel_file = xlrd.open_workbook("book.xlsx") new_file = copy(excel_file) sheet = new_file.get_sheet(0) # 獲取表格的第一個sheet sheet.write(0,1,"測試") # 第一行第二列寫入:測試 sheet.write(1,1,"測試1") # 第二行第二列寫入:測試1 new_file.save("book.xlsx")
運行后book.xlsx表會修改更新
五、封裝操作excel讀和寫的類
通過上面介紹,基本具備使用xlrd、xlwt、xlutils模塊進(jìn)行excel文件數(shù)據(jù)讀取和向excel文件中寫入數(shù)據(jù),在進(jìn)行接口測試時,我們說到需要:測試數(shù)據(jù)和測試腳本分離,后續(xù)的接口測試用例數(shù)據(jù),我們統(tǒng)一寫入excel表格中,然后通過操作excel來讀取測試數(shù)據(jù)并將測試結(jié)果回填到excel中。因此,咱們需要對向excel讀取數(shù)據(jù)和向excel寫入數(shù)據(jù)的操作進(jìn)行封裝。
我們操作上面的api測試用例這個sheet,封裝讀取excel數(shù)據(jù)的類,代碼示例:
from xlrd import open_workbook class 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) # 獲取標(biāo)題行的數(shù)據(jù) for i in range(1, sh.nrows): # 跳過標(biāo)題行,從第二行開始獲取數(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 copy from 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拷貝進(jìn)新的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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python Matplotlib 基于networkx畫關(guān)系網(wǎng)絡(luò)圖
這篇文章主要介紹了Python Matplotlib 基于networkx畫關(guān)系網(wǎng)絡(luò)圖,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07pyqt5 QProgressBar清空進(jìn)度條的實例
今天小編就為大家分享一篇pyqt5 QProgressBar清空進(jìn)度條的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06利用python微信庫itchat實現(xiàn)微信自動回復(fù)功能
最近發(fā)現(xiàn)了一個特別好玩的Python 微信庫itchat,可以實現(xiàn)自動回復(fù)等多種功能,下面這篇文章主要給大家介紹了利用python微信庫itchat實現(xiàn)微信自動回復(fù)功能的相關(guān)資料,需要的朋友可以參考學(xué)習(xí),下面來一起看看吧。2017-05-05python使用writerows寫csv文件產(chǎn)生多余空行的處理方法
這篇文章主要介紹了python使用writerows寫csv文件產(chǎn)生多余空行的處理方法,需要的朋友可以參考下2019-08-08