python - Python Selenium 上的 StaleElementReferenceException

标签 python html selenium-webdriver dom

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

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

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

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

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()

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

最佳答案

这意味着元素不再在 DOM 中,或者它发生了变化。

以下代码将通过控制和忽略 StaleElementExceptions 并像处理任何其他 NoSuchElementException 一样帮助您找到元素。它等待元素不会过时,就像它等待元素出现一样。它也是如何在 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 循环中,并思考在迭代过程中会发生什么:

  1. 当你点击元素(最后一行)时会发生一些变化
  2. 所以页面正在改变
  3. 您进入下一个迭代。现在正在尝试找到一个新元素(循环中的第一行)。
  4. 你找到了元素
  5. 它完成了改变
  6. 你尝试通过获取属性来使用它
  7. 砰!元素是旧的。您在第 4 步得到了它,但它在第 5 步完成了更改

关于python - Python Selenium 上的 StaleElementReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27003423/

相关文章:

python - 如何提取包含文本的 pandas 系列的每一行中的特定数字

python - 有没有办法让 pydev (或任何 Python IDE)理解使用 __import__ 或 exec 导入的模块

javascript - 鼠标向上 - 在 Div 之外单击在移动设备上不起作用

javascript - 从 Java Selenium 执行 JavaScript 库和函数

c# - Selenium xPath 文本连接

python - 如何让多个 Pod 在 Kubernetes 上相互通信

python - Django:上传前调整图像大小

javascript - JQuery.css ("display", "block") 仍然以内联结束

html - Jumbotron 覆盖了其上方 div 的阴影

javascript - 使用 CucumberJs 进行场景失败后截取屏幕截图并重新启动浏览器