Python Selenium上的StaleElementReferenceException [英] StaleElementReferenceException on Python Selenium

查看:348
本文介绍了Python Selenium上的StaleElementReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中使用Selenium时出现以下错误:

I am getting the following error while using Selenium in python:

selenium.common.exceptions.StaleElementReferenceException: Message: u'stale element reference: element is not attached to the page document\n

有趣的是,该错误在for循环中的不同时间弹出.有时它会通过例如. 4次迭代和其他时间,例如. 7.

Interestingly enough, the error pops up at different times in the for loop. Sometimes it gets through eg. 4 iterations and other times eg. 7.

正在运行的一些相关代码是:

Some of the relevant code being run is:

for i in range(0, 22):
    u = driver.find_elements_by_id("data")
    text = u[0].get_attribute("innerHTML")
    driver.find_elements_by_class_name("aclassname")[0].click()

此错误是什么意思,我可以尝试解决什么问题?

What does this error mean and what is something I can try to fix this?

推荐答案

这意味着该元素不再位于DOM中,或者已更改.

It means the element is no longer in the DOM, or it changed.

以下代码将通过控制和忽略 StaleElementExceptions 并像对待其他 NoSuchElementException 一样处理它们,来帮助您找到元素.它等待该元素不过期,就像它等待该元素存在一样.它还是如何正确等待硒中条件的一个很好的例子.

The following code will help you find the element by controlling and ignoring StaleElementExceptions and handling them just like any other NoSuchElementException. It waits for the element to NOT be stale, just like it waits for the element to be present. It also serves as a good example on how to properly wait for conditions in Selenium.

from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions

my_element_id = 'something123'
ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,)
your_element = WebDriverWait(your_driver, some_timeout,ignored_exceptions=ignored_exceptions)\
                        .until(expected_conditions.presence_of_element_located((By.ID, my_element_id)))

为更好地理解问题,假设您处于for循环内,并考虑迭代期间会发生什么:

To better understand the problem, imagine you are inside a for loop and think what happens during the iterations:

  1. 单击元素(最后一行)时,情况会发生变化
  2. 因此页面正在更改
  3. 您输入下一个迭代.现在正在尝试查找新元素(循环中的第一行).
  4. 您找到了元素
  5. 完成更改
  6. 您尝试通过获取属性来使用它
  7. B!元素是旧的.您在第4步中获得了它,但在第5步中完成了更改

这篇关于Python Selenium上的StaleElementReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆