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

查看:28
本文介绍了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

有趣的是,错误在 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 一样处理它们来帮助您找到元素.它等待元素不再陈旧,就像它等待元素存在一样.它也是如何在 Selenium 中正确等待条件的一个很好的例子.

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. 呸!该元素是旧的.您在第 4 步中得到了它,但它在第 5 步中完成了更改

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

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