作自动化,必不可少的是参数化这个步骤了,后期维护用例,方便或者管理方便都少不了参数化这一步。
就讲讲我自己第一次实现参数化的过程和碰到的一些问题的:
首先是安装xlrd模块,网上能找的方法稍微研究一下基本也能用,我来说说实际能用的吧。
使用pip安装,最直接,自动安装相应的目录下,可直接使用。
首先,在安装python+selenium的时候相信是有安装过pip的(没有的可以百度一下python3+selenium环境配置这里不做赘述)
然后使用命令到pip目录下(我的目录如下):
输入pip install xlrd,系统自动安装组xlrd模块,在python中直接引用就可以正常使用了
接下来说一下代码:
这是可以在python3正常读取excel的方法(原方法没有读取列)先读取标题行下的数据行数据,再分别读取每一行的列(excel一个行一个列定位一格数据)存储到字典中,一行作为一个字典,存放到列表中
如果使用原文:https://blog.csdn.net/yzl11/article/details/52832941的方法,无法实现在其他地方点用,若在其他地方调用,会出现表格中数据读取两次的情况(一列数据读取两次,存储两个想通过字典)
def open_excel(file = 'file.xls'):#打开要解析的Excel文件 try: data = xlrd.open_workbook(file) return data except Exception as e: print(e) def excel_by_index(file = 'file.xls', colindex = 0, by_index = 0):#按表的索引读取 data = open_excel(file)#打开excel文件 tab = data.sheets()[by_index]#选择excel里面的Sheet nrows = tab.nrows#行数 ncols = tab.ncols#列数 colName = tab.row_values(colindex)#第0行的值 list = []#创建一个空列表 for x in range(1, nrows): #第一行为标题(第一行为0),所以从第二行开始 row = tab.row_values(x) if row: app = {}#创建空字典 for y in range(0, ncols): app[colName[y]] = row[y] list.append(app) return list
在用例中调用:
def test_user_management(self): listdata = excel_by_index("E:\\data.xlsx") print(listdata) if (len(listdata) <= 0): assert 0, u"Excel数据异常" for i in range(0, len(listdata)): self.driver = webdriver.Chrome() self.driver.implicitly_wait(30) self.driver.maximize_window() # 最大化浏览器 self.driver.get("http://xxxx") self.driver.implicitly_wait(20) self.driver.set_window_size(1440, 900) # 分辨率 1280*800 time.sleep(1) # 点击登录按钮 self.driver.find_element_by_xpath(".//*[@id='userNo']").send_keys(listdata[i]['username']) self.driver.find_element_by_xpath(".//*[@id='pwd']").send_keys(listdata[i]['password']) self.driver.find_element_by_xpath(".//*[@id='subSave']").click() time.sleep(2) if Login_Blog.isElementExist(self, ".//*[@id='main']/div/div[2]/div[1]/div[3]/div[4]/div/span"): pass elif Login_Blog.isTextExist(self, "User Login", ".//*[@id='page-container']/div/div[1]/div/small") and \ Login_Blog.isTextExist(self, "登录失败,请重新登录.", ".//*[@id='showMsg']"): pass elif Login_Blog.isTextExist(self, "User Login", ".//*[@id='page-container']/div/div[1]/div/small") and \ Login_Blog.isTextExist(self, "用户名或密码错误,请重新输入", ".//*[@id='showMsg']"): pass else: assert 0, u"登录失败,找不到右上角头像" self.driver.close()使用键值匹配,分别读取excel中的用户名密码实现登录测试,结果返回在日志中(代码中使用了部分我自己封装的页面检查方法):
使用xlrd主要出现的问题是python3网上说的安装方法直接用过,都一直报错,包括下载安装包安装(可能兼容问题)使用Pychrom直接添加也一直失败,后来去研究了pip安装终于成功(必须cd到pip.exe的目录下才能使用pip命令安装)
第二个问题是网上给出的方法大同小异,基本都不适用(或者适用python2没有试过),根据自己思路做了轻微调整定位行列,前期直接使用网上的方法读取的数据都是重复的,造成用例重复执行了。
希望能给学到这的有一定帮助
参考资料:https://blog.csdn.net/yzl11/article/details/52832941