
python for循环中无法定位元素的解决方法
在python中使用for循环读取excel数据进行登录参数化测试时,有时会出现第一遍执行成功,第二遍报错,无法定位元素的情况。
这个问题通常是由浏览器驱动放在for循环内造成的。为了解决这个问题,需要将浏览器驱动(如webdriver.firefox())置于for循环之外,如下所示:
import unittest
import time
import xlrd
from selenium import webdriver
def 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 list
class 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循环中无法定位元素的原因是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号