如何等到元素出现在 Selenium 中? [英] How to wait until an element is present in 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
?
推荐答案
您需要调用 ignoring
以忽略异常,而 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")));
withTimeout(long, TimeUnit) has become withTimeout(Duration)
pollingEvery(long, TimeUnit) has become pollingEvery(Duration)
所以代码看起来像这样:
So the code will look as such:
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30)
.pollingEvery(Duration.ofMillis(200)
.ignoring(NoSuchElementException.class);
等待的基本教程可以在这里找到.
Basic tutorial for waiting can be found here.
这篇关于如何等到元素出现在 Selenium 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!