Python Selenium 上的 StaleElementReferenceException

新手上路,请多包涵

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

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

原文由 bill999 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 656
1 个回答

这意味着该元素不再在 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 步完成更改

原文由 Emilio 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏