如何在使用ExpectedConditions.attributeToBe时避免StaleElementReferenceException?

huangapple go评论70阅读模式
英文:

How to avoid StaleElementReferenceException when using ExpectedConditions.attributeToBe?

问题

我正在尝试验证元素的属性 "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: 元素过时的引用:元素未连接到页面文档
英文:

I am trying to validate the attribute "innerText" of an element is updated (eg, from 100 to 50). To avoid using sleeps I am waiting for the attributeToBe. But I am receiving StaleElementReferenceException exception. Probably, because the DOM is reloaded. mportant note: The element is visible, present and without this the element.getText() returns the old value. So the test fails (because the attribute has the old value).

For now, I am ignoring the exception but would you suggest a better solution, please?

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

Exception:

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

答案1

得分: 0

如果有人需要帮助,我通过使用元素定位器来代替在参数中传递网页元素来修复了这个问题。这就是我之前遇到 StaleElementReferenceException 的原因,因为元素正在被刷新,而我却在访问旧元素。

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

In case someone needs help on that, I fixed it by using the element locator instead of passing the webelement in the parameter. This was the why I was having the StaleElementReferenceException since the element was getting refreshed and I was accessing the old one.

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

huangapple
  • 本文由 发表于 2020年9月16日 15:17:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63914977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定