【问题标题】:How to avoid StaleElementReferenceException when using ExpectedConditions.attributeToBe?使用 ExpectedConditions.attributeToBe 时如何避免 StaleElementReferenceException?
【发布时间】:2021-01-02 23:39:51
【问题描述】:

我正在尝试验证元素的属性“innerText”是否已更新(例如,从 100 到 50)。为了避免使用睡眠,我正在等待attributeToBe。但我收到 StaleElementReferenceException 异常。可能是因为 DOM 被重新加载了。重要说明:该元素是可见的,存在的,没有这个 element.getText() 返回旧值。所以测试失败(因为属性有旧值)。

目前,我忽略了这个例外,但是请您提出一个更好的解决方案吗?

public void waitAttributeToBe(WebElement webElement, String text) {
        try {
            wait.until(ExpectedConditions.attributeToBe(webElement,"innerText", text));
        } catch (StaleElementReferenceException exc) {
            exc.printStackTrace();
        }
}

例外:

 org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

【问题讨论】:

  • 你能在dom重新加载后获取元素然后试试这个条件吗?
  • 希望这个回答能帮到你Link
  • 你能粘贴整个脚本吗?
  • @vishalgada 你的意思是重新实例化webelement吗?我正在使用 Page 工厂,该元素是在 Page 类中声明的。
  • @Maria 你能尝试使用下面的代码来实例化pagefactory PageFactory.initElements(new AjaxElementLocatorFactory(driver, TimeoutValue), this);

标签: java selenium webdriverwait


【解决方案1】:

如果有人需要帮助,我通过使用元素定位器而不是在参数中传递 webelement 来修复它。这就是我出现 StaleElementReferenceException 的原因,因为元素正在刷新并且我正在访问旧元素。

public void waitAttributeToBe(By by, String attribute, String text) {
        wait.until(ExpectedConditions.attributeToBe(by, attribute, text));
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2016-02-14
    • 2016-03-24
    • 2012-07-04
    • 1970-01-01
    相关资源
    最近更新 更多