基于Python的接口自動(dòng)化讀寫excel文件的方法
使用python進(jìn)行接口測(cè)試時(shí)常常需要接口用例測(cè)試數(shù)據(jù)、斷言接口功能、驗(yàn)證接口響應(yīng)狀態(tài)等,如果大量的接口測(cè)試用例腳本都將接口測(cè)試用例數(shù)據(jù)寫在腳本文件中,這樣寫出來(lái)整個(gè)接口測(cè)試用例腳本代碼將看起來(lái)很冗余和難以清晰的閱讀以及維護(hù),試想如果所有的接口測(cè)試數(shù)據(jù)都寫在代碼中,接口參數(shù)或者測(cè)試數(shù)據(jù)需要修改,那不得每個(gè)代碼文件都要一一改動(dòng)?。因此,這種不高效的模式不是我們想要的。所以,在自動(dòng)化測(cè)試中就有個(gè)重要的思想:測(cè)試數(shù)據(jù)和測(cè)試腳本分離,也就是測(cè)試腳本只有一份,其中需要輸入數(shù)據(jù)的地方會(huì)用變量來(lái)代替,然后把測(cè)試輸入數(shù)據(jù)單獨(dú)放在一個(gè)文件中,這個(gè)存放測(cè)試輸入數(shù)據(jù)的文件,通常是表格的形式或者其他格式文件,如excel文件、json文件、xml文件、txt文本文件等等。在python進(jìn)行接口自動(dòng)化測(cè)試時(shí),為了方便管理和存儲(chǔ)測(cè)試用例數(shù)據(jù),一般將測(cè)試數(shù)據(jù)編寫存儲(chǔ)在excel文件中,測(cè)試腳本通過(guò)讀取excel文件來(lái)實(shí)現(xiàn)測(cè)試數(shù)據(jù)加載,并運(yùn)行得出測(cè)試用例數(shù)據(jù)執(zhí)行的結(jié)果,并回寫測(cè)試結(jié)果到excel文件中,這樣就實(shí)現(xiàn)了測(cè)試腳本和數(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 xlrdpip install xlwtpip install xlutils
2.在PyCharm中安裝
直接檢索需要安裝的模塊名稱即可,如xlrd:
新建一個(gè)excel文件,文件名稱:excel_test.xlsx,文件編輯有兩個(gè)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] # 通過(guò)sheet下標(biāo)獲取,第一個(gè)sheet下標(biāo)為0sheet_name2 = file.sheet_by_index(0).name # 通過(guò)sheet索引獲取sheet名print(all_sheet)print(sheet_name1)print(sheet_name2)-----------------------------------------# 返回結(jié)果[’員工信息表’, ’api測(cè)試用例’]員工信息表員工信息表
(2)獲取sheet工作表頁(yè)的對(duì)象
代碼示例:
import xlrdfile = xlrd.open_workbook('excel_test.xlsx')sheet_name1 = file.sheet_names()[0]sheet1_obj = file.sheet_by_name(sheet_name1) # 通過(guò)sheet名獲取sheet對(duì)象sheet2_obj = file.sheet_by_index(1) # 通過(guò)sheet索引獲取sheet對(duì)象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) # 通過(guò)sheet索引獲取sheet對(duì)象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ù)直接返回成浮點(diǎn)數(shù)了
常見(jiàn)讀取excel不同數(shù)據(jù)類型的返回問(wèn)題,如讀取日期格式的數(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ù)為浮點(diǎn)數(shù)的處理方式:
代碼如下:
import xlrdfrom datetime import datefile = xlrd.open_workbook('excel_test.xlsx')sheet = file.sheet_by_index(0) # 通過(guò)sheet索引獲取sheet對(duì)象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ù),返回的是浮點(diǎn)數(shù)data_value = xlrd.xldate_as_tuple(sheet.cell_value(1,2) ,file.datemode) # xldate_as_tuple()方法得到日期數(shù)據(jù)年月日時(shí)分秒的值并返回為元組datatime2 = date(*data_value[:3]).strftime(’%Y/%m/%d’) # 截取元組中的前三位,即年月日的值傳給data,并進(jìn)行時(shí)間格式化 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ù),簡(jiǎn)單示例如下:
import xlwt workbook = xlwt.Workbook(encoding = ’utf-8’) # 創(chuàng)建工作簿sheet = workbook.add_sheet(’api_test’) # 添加一個(gè)sheetdata = sheet.write(0,0,’test’) # 向第一行第一列寫入數(shù)據(jù):testworkbook.save(’book.xlsx’) # 保存到book.xlsx中
運(yùn)行完成后會(huì)在該py文件的同級(jí)目錄下生成一個(gè)book.xlsx的excel文件,并新增了api_test的sheet表名,第一行第一列寫入數(shù)據(jù):test
向excel寫入數(shù)據(jù)時(shí),可以設(shè)置單元格長(zhǎng)寬、單元格合并、寫入時(shí)間格式數(shù)據(jù)以及添加超鏈接等
代碼示例:
import xlwtimport datetimeworkbook = xlwt.Workbook(encoding = ’utf-8’) # 創(chuàng)建工作簿sheet = workbook.add_sheet(’api_test’) # 添加一個(gè)sheetdata = sheet.write(4,0,’test’) sheet.col(0).width = 5000 # 設(shè)置單元格寬度 style = xlwt.XFStyle() # 初始化表格樣式style.num_format_str = ’M/D/YY’ # 設(shè)置時(shí)間格式,如:M/D/YYsheet.write(5, 1, datetime.datetime.now(), style) # 寫入時(shí)間格式數(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中
運(yùn)行后輸出excel效果如下:
(1)拷貝excel表格
xlutils模塊下的copy可以復(fù)制拷貝excel文件,代碼示例:
import xlrdfrom xlutils.copy import copyexcel_file = xlrd.open_workbook('book.xlsx')new_file = copy(excel_file) # 拷貝文件對(duì)象new_file.save('book1.xlsx') # 保存為excel文件
運(yùn)行以上代碼會(huì)在同級(jí)目錄下生成一個(gè)book1.xlsx的excel文件,該文件和book.xlsx一樣,只是文件名稱不一樣而已,也就是復(fù)制excel文件了
(2)修改excel文件內(nèi)容
除了copy為其他excel文件外,也可以直接copy文件修改后,保存為同名的文件,那修改的內(nèi)容將直接覆蓋原excel文件,達(dá)到修改的目的
示例:
import xlrdfrom xlutils.copy import copyexcel_file = xlrd.open_workbook('book.xlsx')new_file = copy(excel_file)sheet = new_file.get_sheet(0) # 獲取表格的第一個(gè)sheetsheet.write(0,1,'測(cè)試') # 第一行第二列寫入:測(cè)試sheet.write(1,1,'測(cè)試1') # 第二行第二列寫入:測(cè)試1new_file.save('book.xlsx')
運(yùn)行后book.xlsx表會(huì)修改更新
五、封裝操作excel讀和寫的類通過(guò)上面介紹,基本具備使用xlrd、xlwt、xlutils模塊進(jìn)行excel文件數(shù)據(jù)讀取和向excel文件中寫入數(shù)據(jù),在進(jìn)行接口測(cè)試時(shí),我們說(shuō)到需要:測(cè)試數(shù)據(jù)和測(cè)試腳本分離,后續(xù)的接口測(cè)試用例數(shù)據(jù),我們統(tǒng)一寫入excel表格中,然后通過(guò)操作excel來(lái)讀取測(cè)試數(shù)據(jù)并將測(cè)試結(jié)果回填到excel中。因此,咱們需要對(duì)向excel讀取數(shù)據(jù)和向excel寫入數(shù)據(jù)的操作進(jìn)行封裝。
我們操作上面的api測(cè)試用例這個(gè)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) # 獲取標(biāo)題行的數(shù)據(jù) for i in range(1, sh.nrows): # 跳過(guò)標(biāo)題行,從第二行開始獲取數(shù)據(jù) col_datas = dict(zip(header, sh.row_values(i))) # 將每一行的數(shù)據(jù),組裝成字典 data_list.append(col_datas) # 將字典添加到列表中 ,列表嵌套字典,每個(gè)元素就是一個(gè)字典 return data_list if __name__ == ’__main__’: Readexcel()
上面代碼封裝了讀取excel數(shù)據(jù)的類,將每一行數(shù)據(jù)讀取出來(lái)組裝成字典并添加到列表中
實(shí)例化運(yùn)行:
data_list = Readexcel().excel_data_list(’excel_test.xlsx’,’api測(cè)試用例’) 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’: ’分頁(yè)查詢視頻安防設(shè)備列表’, ’files’: ’’}, {’module’: ’平臺(tái)管理’, ’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)用管理-單個(gè)應(yīng)用系統(tǒng)添加’, ’files’: ’’}, {’module’: ’平臺(tái)管理’, ’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’: ’平臺(tái)管理’, ’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è)備分類-分頁(yè)獲取設(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: 實(shí)際結(jié)果 :param test_res: 測(cè)試結(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個(gè)sheet,0表示第一個(gè)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ù)接口測(cè)試數(shù)據(jù)的讀取和寫入就依靠這兩個(gè)類了。
到此這篇關(guān)于基于Python的接口自動(dòng)化讀寫excel文件的文章就介紹到這了,更多相關(guān)Python接口自動(dòng)化內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. JSP的Cookie在登錄中的使用2. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼3. HTML5 Canvas繪制圖形從入門到精通4. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法5. 利用CSS3新特性創(chuàng)建透明邊框三角6. ASP基礎(chǔ)知識(shí)VBScript基本元素講解7. 詳解CSS偽元素的妙用單標(biāo)簽之美8. XHTML 1.0:標(biāo)記新的開端9. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究10. XML入門的常見(jiàn)問(wèn)題(四)
