
python for循环中无法定位元素的解决方法
在python中使用for循环读取excel数据进行登录参数化测试时,有时会出现第一遍执行成功,第二遍报错,无法定位元素的情况。
这个问题通常是由浏览器驱动放在for循环内造成的。为了解决这个问题,需要将浏览器驱动(如webdriver.firefox())置于for循环之外,如下所示:
import unittestimport timeimport xlrdfrom selenium import webdriverdef open_excel(file='file.xls'): try: data = xlrd.open_workbook(file) return data except Exception as e: print(str(e))def excel_table_byindex(file='file.xls', colnameindex=0, by_index=0): data = open_excel(file) table = data.sheets()[by_index] nrows = table.nrows #行数 colnames = table.row_values(colnameindex) #某一行数据 list = [] for rownum in range(1, nrows): row = table.row_values(rownum) if row: app = {} for i in range(len(colnames)): app[colnames[i]] = row[i] list.append(app) return listclass login(unittest.TestCase): @classmethod def setUpClass(cls): # 将浏览器驱动置于for循环外 cls.dr = webdriver.Firefox() cls.dr.maximize_window() cls.dr.implicitly_wait(10) def test(self): tabls = excel_table_byindex(file='./data/meit.xlsx') # 遍历数据表 for i in range(0, len(tabls)): self.dr.get("https://passport.meituan.com/account/unitivelogin?service=www&continue=http%3A%2F%2Fwww.meituan.com%2Faccount%2Fsettoken%3Fcontinue%3Dhttps%253A%252F%252Fwww.meituan.com%252F") time.sleep(5) # 输入登录信息 self.dr.find_element_by_id('login-email').send_keys(tabls[i]['username']) self.dr.find_element_by_id("login-password").send_keys(tabls[i]['password']) self.dr.find_element_by_class_name('btn').click() time.sleep(3) @classmethod def tearDownClass(cls): time.sleep(3) cls.dr.quit()if __name__ == '__main__': unittest.main()
通过把浏览器驱动移到setupclass方法中,可以确保在整个测试用例运行期间只创建和关闭一次浏览器驱动,从而避免了因重复创建和关闭浏览器驱动而造成的无法定位元素的问题。
立即学习“Python免费学习笔记(深入)”;
以上就是Python for循环中无法定位元素的原因是什么?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1350587.html
微信扫一扫
支付宝扫一扫