The element reference of...is stale; either the element is no longer attached to the DOM,的报错处理


今天用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()


附参考文章:点击打开链接



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值