
python for循环中元素定位失效
在使用 python 中的 for 循环读取 excel 数据进行登录参数化测试时,开发者可能会遇到一个问题,即第一遍执行成功,而第二遍却报错,无法定位元素。
解决方案:在 for 循环外部调用浏览器
对于这个特定问题,解决方法是将浏览器的调用放在 for 循环的外部。修改后的测试代码示例如下:
立即学习“Python免费学习笔记(深入)”;
import unittestimport timeimport xlrdfrom selenium import webdriverdef open_excel(file): try: data = xlrd.open_workbook(file) return data except Exception as e: print(str(e))def excel_table_byindex(file, 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): def setUp(self): self.driver = webdriver.Firefox() self.driver.maximize_window() self.driver.implicitly_wait(10) self.driver.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) def test(self): tabls = excel_table_byindex(file='./data/meit.xlsx') print(tabls) if (len(tabls) <= 0): assert 0, u"数据异常" for i in range(0, len(tabls)): print(i) print(tabls[i]['username']) print(tabls[i]['password']) # 登录 self.driver.find_element_by_id('login-email').send_keys(tabls[i]['username']) self.driver.find_element_by_id("login-password").send_keys(tabls[i]['password']) self.driver.find_element_by_class_name('btn').click() time.sleep(3) def tearDown(self): time.sleep(3) self.driver.quit()if __name__ == '__main__': unittest.main()
通过将浏览器的初始化和退出操作移动到 for 循环之外,我们可以确保每次迭代都使用一个新的浏览器实例。这样,就不会出现元素定位失效的问题。
以上就是Python For循环中元素定位失效:为什么在 Excel 参数化测试中,循环执行后定位元素失败,而调整浏览器调用位置后就能解决问题?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1350808.html
微信扫一扫
支付宝扫一扫