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

Pythonfor循环中无法定位元素的原因是什么?

网络教程 app 1℃

Pythonfor循环中无法定位元素的原因是什么

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("passport.meituan./account/unitivelogin?service=www&continue=http%3A%2F%2Fwww.meituan.%2Faccount%2Fsettoken%3Fcontinue%3Dhttps%253A%252F%252Fwww.meituan.%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 for循环中无法定位元素的原因是什么?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » Pythonfor循环中无法定位元素的原因是什么?

喜欢 (0)