基于Excel参数化你的Selenium2测试代码
上一篇 /
下一篇 2017-04-06 14:51:56
/ 个人分类:selenium
前言
今天我们就如何使用xlrd模块来进行python selenium2 + excel自动化测试过程中的参数化进行演示说明,以解决大家在自动化测试实践过程中参数化的疑问。
环境安装
xlrd是python用于读取excel的第三方扩展包,因此在使用xlrd前,需要使用以下命令来安装xlrd。
pipinstallxlrd
xlrd基本用法
- 导入扩展包
importxlrd
- 打开excel文件
excel = xlrd.open_workbook(u'excelFile.xls')
- 获取工作表
通过索引顺序获取
table = excel.sheets()[0]
table = excel.sheet_by_index(0)
通过工作表名获取
table = excel.sheet_by_name(u'Sheet1')
- 获取行数和列数
获取行数
nrows =table.nrows获取列数
ncols =table.ncols
- 获取整行或整列的值
其中i为行号, j为列号
行号、列号索引从0开始
row_values =table.row_values(i)
col_values =table.col_values(j)
- 获取指定单元格数据
i行号, j 列号
value =table.cell(i, j).value例如获取第一行、第一列的数据
value =table.cell(0,0).value
- 循环行遍历列表数据
先获取行数
nrows =table.nrows遍历打印所有行数据foriinrange(0, nrows):
printtable.row_values(i)
至此我们将xlrd基本常用的技巧和方法都一一列举完毕,下面我们一起看一下如何利用xlrd来实现python selenium2自动化测试参数化。代码示例
我们以上一章我们的第一个python selenium2测试代码为蓝本,进行改造,从excel中读取以下格式的数据来进行测试,
请将下列表格数据存入名为baidu_search.xlsx的excel文件。
excel_demo.png
__author__ =u'苦叶子'fromseleniumimportwebdriverimportunittestimportHTMLTestRunnerimportsysfromtimeimportsleepimportxlrd
reload(sys)
sys.setdefaultencoding("utf-8")classLoadBaiduSearchTestData:def__init__(self, path):self.path = pathdefload_data(self):excel = xlrd.open_workbook(self.path)table = excel.sheets()[0]nrows = table.nrowstest_data = []foriinrange(1, nrows):
test_data.append(table.row_values(i))returntest_dataclassBaiduTest(unittest.TestCase):"""百度首页搜索测试用例"""defsetUp(self):self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url =u"http://www.baidu.com"self.path =u"baidu_search.xlsx"deftest_baidu_search(self):driver = self.driverprintu"开始[case_0001]百度搜索"test_excel = LoadBaiduSearchTestData(self.path)
data = test_excel.load_data()printdatafordindata:driver.get(self.base_url)self.assertEqual(driver.title,u"百度一下,你就知道")
sleep(1)
driver.find_element_by_id("kw").clear()driver.find_element_by_id("kw").send_keys(d[1])
sleep(1)
driver.find_element_by_id("su").click()
sleep(1)self.assertEqual(driver.title, d[2])
sleep(2)deftearDown(self):self.driver.quit()if__name__ =='__main__':
testunit = unittest.TestSuite()
testunit.addTest(BaiduTest('test_baidu_search'))htmlPath =u"testReport.html"fp = file(htmlPath,"wb")
runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
title=u"百度测试",
description=u"测试用例结果")
runner.run(testunit)
fp.close()
总结
在上文中,我们详细的描述了xlrd操作excel的各种方法和技巧,以及封装xlrd读取excel实现在python selenium自动化测试过程参数化相应的输入数据和期望结果。
最重要的还是需要大家自己多练习相关的代码,并能做相应的扩展, 同时要去有针对性的学习对应的库,深入了解其使用方法和技巧,甚至原理。
相关阅读:
- Windows 7下的Excel 2010同时打开多个独立的窗口 (szdgz, 2016-4-27)
- VBS之excel操作集锦 (幽幽草哈哈, 2016-7-08)
- Excel导入导出用例设计总结 (susan12, 2016-8-11)
- python处理excel文件 (若尘_51, 2016-11-14)
- SoapUI接口测试(四)使用EXCEL参数化 (vs_dev, 2016-11-26)
- webdriver python Excel操作 (ice1016, 2016-12-19)
- java 读取本地excel文件 遇到不需要的列跳过 (susan12, 2017-3-19)
- 按列读取excel数据 遇到不需要的列跳过 (susan12, 2017-3-21)
- 读取出了excel后 把值拼成list (susan12, 2017-3-23)
- 基于Excel参数化你的Selenium2测试代码 (launcelot, 2017-4-06)
收藏
举报
TAG:
Excel