微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

动态等待元素变得可点击不起作用

如何解决动态等待元素变得可点击不起作用

我写了一个函数如下

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() 时,这也有效,但这需要我手动输入睡眠时间,这就是我正在做的。我希望这是动态的。感谢任何帮助或建议。

解决方法

有时 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();
,

可能这不是一个好主意,但我认为除了在那里添加一些睡眠之外,没有其他稳定的解决方案。 所以,请试试这个:

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();
driver.findElement(By.xpath(home));
libraryUtils.waitForElements.waitForElementToBeClickable(driver,homeButton,20);
try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
}
driver.findElement(By.xpath(home)).click();
,

这里的问题是您已经在 element.click() 函数中执行 waitForElementToBeClickable 并在调用此函数时再次调用 click。

libraryUtils.waitForElements.waitForElementToBeClickable(driver,20).click();

由于您在等待元素可点击时已经点击了,所以您不应再次点击它。我希望你能得到StaleElementException

的答案

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。