我正在尝试让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")));
*Update for newer 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。
WebDriverWait wait = new WebDriverWait(driver,5)
wait.until(ExpectedConditions.visibilityOf(element));
你可以在加载整个页面代码执行和抛出错误之前使用它。时间是秒
我建议你使用Selenide库。它允许编写更简洁和可读的测试。它可以等待语法更短的元素的存在:
$("#elementId").shouldBe(visible);
以下是测试Google搜索的示例项目:https://github.com/selenide-examples/google
public WebElement fluientWaitforElement(WebElement element, int timoutSec, int pollingSec) {
FluentWait<WebDriver> fWait = new FluentWait<WebDriver>(driver).withTimeout(timoutSec, TimeUnit.SECONDS)
.pollingEvery(pollingSec, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class, TimeoutException.class).ignoring(StaleElementReferenceException.class);
for (int i = 0; i < 2; i++) {
try {
//fWait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@id='reportmanager-wrapper']/div[1]/div[2]/ul/li/span[3]/i[@data-original--title='We are processing through trillions of data events, this insight may take more than 15 minutes to complete.']")));
fWait.until(ExpectedConditions.visibilityOf(element));
fWait.until(ExpectedConditions.elementToBeClickable(element));
} catch (Exception e) {
System.out.println("Element Not found trying again - " + element.toString().substring(70));
e.printStackTrace();
}
}
return element;
}
FluentWait抛出NoSuchElementException是混乱的情况
org.openqa.selenium.NoSuchElementException;
同
java.util.NoSuchElementException
在
.ignoring(NoSuchElementException.class)