
python for循环中元素定位失效
在使用 python 中的 for 循环读取 excel 数据进行登录参数化测试时,开发者可能会遇到一个问题,即第一遍执行成功,而第二遍却报错,无法定位元素。
解决方案:在 for 循环外部调用浏览器
对于这个特定问题,解决方法是将浏览器的调用放在 for 循环的外部。修改后的测试代码示例如下:
立即学习“Python免费学习笔记(深入)”;
import unittest
import time
import xlrd
from selenium import webdriver
def 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 list
class 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 参数化测试中,循环执行后定位元素失败,而调整浏览器调用位置后就能解决问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号