如何让 Selenium 等待元素出现?

新手上路,请多包涵

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

 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

原文由 Steve Chambers 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 577
2 个回答

您需要调用 ignoring 忽略异常,而 WebDriver 将等待。

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

有关详细信息,请参阅 FluentWait 的文档。但请注意,此条件已在 ExpectedConditions 中实现,因此您应该使用:

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

*较少版本的硒

 withTimeout(long, TimeUnit) has become withTimeout(Duration)
pollingEvery(long, TimeUnit) has become pollingEvery(Duration)

所以代码看起来像这样:

 FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
        .withTimeout(Duration.ofSeconds(30)
        .pollingEvery(Duration.ofMillis(200)
        .ignoring(NoSuchElementException.class);

可以在 此处 找到有关等待的基本教程。

原文由 Petr Mensik 发布,翻译遵循 CC BY-SA 4.0 许可协议

利用:

 WebDriverWait wait = new WebDriverWait(driver, 5)
wait.until(ExpectedConditions.visibilityOf(element));

您可以在加载整个页面之前的某个时间使用它,代码被执行并抛出错误。时间以秒为单位。

原文由 bhupendra 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题