如何等到Selenium中存在元素? [英] How to wait until an element is present in Selenium?

查看:157
本文介绍了如何等到Selenium中存在元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让Selenium等待页面加载后动态添加到DOM的元素。试过这个:

I'm trying to make Selenium wait for an element that is dynamically added to the DOM after page load. Tried this:

fluentWait.until(ExpectedConditions.presenceOfElement(By.id("elementId"));

如果有帮助,这里是 fluentWait

FluentWait fluentWait = new FluentWait<>(webDriver) {
    .withTimeout(30, TimeUnit.SECONDS)
    .pollingEvery(200, TimeUnit.MILLISECONDS);
}

但它抛出一个 NoSuchElementException - 看起来像 presenceOfElement 期望元素存在,所以这是有缺陷的。这必须是面包和黄油到Selenium并且不想重新发明轮子......任何人都可以建议一个替代方案,理想情况下没有滚动我自己的 Predicate

But it throws a NoSuchElementException - looks like presenceOfElement expects the element to be there so this is flawed. This must be bread and butter to Selenium and don't want to reinvent the wheel... could anyone suggest an alternative, ideally without rolling my own Predicate?

推荐答案

你需要调用忽略,但要忽略 WebDriver 将等待。

You need to call ignoring with exception to ignore while the WebDriver will wait.

FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
        .withTimeout(30, TimeUnit.SECONDS)
        .pollingEvery(200, TimeUnit.MILLISECONDS)
        .ignoring(NoSuchElementException.class);

请参阅 FluentWait 了解更多信息。但请注意,此条件已在 ExpectedConditions 所以你应该使用

See the documentation of FluentWait for more info. But beware that this condition is already implemented in ExpectedConditions so you should use

WebElement element = (new WebDriverWait(driver, 10))
   .until(ExpectedConditions.elementToBeClickable(By.id("someid")));

可以找到等待的基本教程这里

Basic tutorial for waiting can be found here.

这篇关于如何等到Selenium中存在元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆