首页 > 解决方案 > 动态等待元素变为可点击不起作用

问题描述

我写了一个函数如下

public static WebElement waitForElementToBeClickable(WebDriver driver, WebElement webElement, int seconds) {
    
    WebDriverWait wait = new WebDriverWait(driver, seconds);
    WebElement element = wait.until(ExpectedConditions.elementToBeClickable(webElement));
    element.click();
    return element;
    
}

现在我正在导入这个函数并使用它如下

private String loginButton = "btnActive";
private String home = "//a[@id='pt1:_UIShome']";
WebElement login = driver.findElement(By.id(loginButton));
libraryUtils.waitForElements.waitForElementToBeClickable(driver, login, 20).click();
WebElement homeButton = driver.findElement(By.xpath(home));
libraryUtils.waitForElements.waitForElementToBeClickable(driver, homeButton, 20).click();
    

单击登录按钮,但在转到下一页后,我收到以下错误 -

org.openqa.selenium.StaleElementReferenceException:过时的元素引用:元素未附加到页面文档

Xpath 是正确的,我已经检查过了。当我使用 时element.click(),这也可以,但那将需要我手动输入睡眠时间,这就是我正在做的事情。我希望这是动态的。感谢任何帮助或建议。

标签: javaseleniumselenium-webdriverautomationrpa

解决方案


有时 JS 还没有完成运行,如果你尝试与web 元素web 元素交互,你会看到staleElemenent exception.

但是,以下解决方案可能对您有用:

new WebDriverWait(driver, 10).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@id='pt1:_UIShome']")));
driver.findElement(By.xpath("//a[@id='pt1:_UIShome']")).click();

推荐阅读