本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

PythonFor循环中元素定位失效:为什么在Excel参数化测试中_循环执行后定位元素失败_而调整浏览器调用位置后就能解决问题?

网络教程 app 1℃

PythonFor循环中元素定位失效为什么在Excel参数化测试中_循环执行后定位元素失败_而调整浏览器调用位置后就能解决问题

python for循环中元素定位失效

在使用 python 中的 for 循环读取 excel 数据进行登录参数化测试时,开发者可能会遇到一个问题,即第一遍执行成功,而第二遍却报错,无法定位元素。

解决方案:在 for 循环外部调用浏览器

对于这个特定问题,解决方法是将浏览器的调用放在 for 循环的外部。修改后的测试代码示例如下:

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("passport.meituan./account/unitivelogin?service=www&continue=http%3A%2F%2Fwww.meituan.%2Faccount%2Fsettoken%3Fcontinue%3Dhttps%253A%252F%252Fwww.meituan.%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 参数化测试中,循环执行后定位元素失败,而调整浏览器调用位置后就能解决问题?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » PythonFor循环中元素定位失效:为什么在Excel参数化测试中_循环执行后定位元素失败_而调整浏览器调用位置后就能解决问题?

喜欢 (0)