gpt4 book ai didi

java - 如何让 Selenium 等到元素出现?

转载 作者:IT老高 更新时间:2023-10-28 20:31:23 25 4
gpt4 key购买 nike

我试图让 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

最佳答案

您需要调用 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")));

*Fewer versions of Selenium :

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);

等待的基础教程见here .

关于java - 如何让 Selenium 等到元素出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20903231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com