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

How to avoid StaleElementReferenceException when using ExpectedConditions.attributeToBe?

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

现在,我忽略了这个例外,但你能建议一个更好的解决方案吗?

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

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

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