今天用python 写脚本时,需要遍历一个列表中的元素,但是遍历到其中某一个元素时,页面报错:
Traceback (most recent call last):
File "E:/work/pythonPro/pythonProject/SalaryBill/test.py", line 107, in <module>
t.test_checkHelp()
File "E:/work/pythonPro/pythonProject/SalaryBill/test.py", line 84, in test_checkHelp
print(ele.text)
File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 76, in text
return self._execute(Command.GET_ELEMENT_TEXT)['value']
File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 628, in _execute
return self._parent.execute(command, params)
File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute
self.error_handler.check_response(response)
File "C:\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <li class="b-b"> is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
问题出现的原因有两种,一种是元素被删了,所以找不到元素导致的错误;第二种是我遇到的,虽然页面看起来没什么变化,但是某个时候页面发生了重载,所以之前定位的元素失效。这时候来点击原本定位的元素时就会报上方错误。此时解决办法需要重新定位元素,然后对元素进行操作。
下方为初始报错代码:
eles = self.driver.find_elements_by_css_selector('li.b-b') for ele in eles: ele.click()
下方为优化后的代码:
for i in range(1,8): csspath='li.b-b:nth-of-type('+str(i)+")" ele = self.driver.find_element_by_css_selector(csspath) ele.click()
附参考文章:点击打开链接