等待元素变得陈旧,为什么“ExpectedConditions.stalenessOf”不起作用?

2024-03-24

我创建了以下方法:

public void waitAndClickElement(WebElement element) throws InterruptedException {
    try {
        Boolean elementPresent = this.wait.until(ExpectedConditions.elementToBeClickable(element)).isEnabled();
        if (elementPresent == true && element.isDisplayed()) {
            element.click();
            System.out.println("Clicked on the element: " + element.getText());
        }
    } catch (StaleElementReferenceException elementUpdated) {
        Boolean elementPresent = wait.until(ExpectedConditions.stalenessOf(element));
        if (elementPresent == true) {
            WebElement staleElement = element;
            staleElement.click();
            System.out.println("Clicked on the 'Stale' element: " + element.getText());
        }
    } catch (NoSuchElementException e) {
        System.out.println("Exception! - Could not click on the element: " + element.getText() + ", Exception: "+ e.toString());
        throw (e);
    } finally {
    }
}

但我似乎仍然遇到以下异常:

Expected condition failed: waiting for element (Proxy element for: DefaultElementLocator 'By.xpath: //a[text()='Exchange Now »']') to become stale (tried for 20 second(s) with 500 MILLISECONDS interval) enter image description here

但同样的方法适用于 20 个构建中的 18 个,有什么想法吗?

谢谢你的帮助


您问题的直接答案是您正在等待一个已经过时的元素变得过时。我不确定你的意图是什么。

您的功能过于复杂,不会像您想象的那样工作。

如果某个元素可单击,它也会启用并显示,因此您无需检查所有三个元素。如果该元素抛出一个StaleElementReferenceException,它不会变得“不新鲜”。

我建议您用下面的函数替换当前的函数。

public void waitAndClickElement(By locator)
{
    try
    {
        this.wait.until(ExpectedConditions.elementToBeClickable(locator)).click();
    }
    catch (TimeoutException e)
    {
        System.out.println("Count not click element <" + locator.toString() + ">");
    }
}

传递定位器而不是元素而不是元素本身,这会简化很多事情。如果该元素存在并且可单击,则会单击该元素。如果它不存在或永远不可点击,它将抛出一个TimeoutException你可以抓住的。

另外,写element.toString()将为该元素写入一些人类可读或无意义的 ID。你最好写一下locator.toString()这将返回定位器的类型,例如By.cssSelector: #hplogo.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

等待元素变得陈旧,为什么“ExpectedConditions.stalenessOf”不起作用? 的相关文章

随机推荐