我在FluentWait
和WebDriverWait
之间感到困惑。
FluentWait
和WebDriverwait
都使用相同的功能,如忽略异常,更改轮询时间间隔,预期条件等。
根据我的理解,两者都实现了Wait
接口。另外WebDriverWait
延伸FluentWait
(这意味着所有功能也存在于WebDriverWait
)。
在WebDriverWait
中没有FluentWait
拥有的额外功能有哪些?
两者之间实际上差别很小。根据WebDriverWait
源代码,它说:
它将忽略
NotFoundException
条件中默认遇到(抛出)的until
实例,并立即传播所有其他实例。您可以通过调用ignoring(exceptions to add)
向忽略列表中添加更多内容
唯一的区别是默认情况下,在WebDriverWait
中忽略了未找到的异常。其余的特征与FluentWait
完全相同,因为WebDriverWait
扩展了它。
FluentWait和WebDriverWait都是Wait接口的实现。
使用Fluent WebDriver显式等待和WebDriver显式等待的目标或多或少相同。但是,在少数情况下,FluentWait可以更灵活。由于这两个类都是相同Wait接口的实现,因此或多或少都具有相同的功能,除了FluentWait具有接受谓词或函数作为参数的功能,直到方法。另一方面,WebDriverWait仅接受函数作为ExpectedCondition in until方法,该方法限制您仅使用布尔返回。当您在FluentWait中使用Predicate时,它允许您从方法返回任何Object。
示例:FluentWait将函数作为参数,直到返回String:
public void exampleOfFluentWait() {
WebElement foo = driver.findElement(By.id("foo"));
new FluentWait<WebElement>(foo)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(2, TimeUnit.SECONDS)
.until(new Function<WebElement, String>() {
@Override
public String apply(WebElement element) {
return element.getText();
}
});
}
具有布尔函数的相同FluentWait作为参数直到方法。
public void exampleOfFluentWait() {
WebElement foo = driver.findElement(By.id("foo"));
new FluentWait<WebElement>(foo)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(2, TimeUnit.SECONDS)
.until(new Function<WebElement, Boolean>() {
@Override
public Boolean apply(WebElement element) {
return element.getText().contains("foo");
}
});
}
还有一个带有谓词的FluentWait。
public void exampleOfFluentWithPredicate() {
WebElement foo = driver.findElement(By.id("foo"));
new FluentWait<WebElement>(foo)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(100, TimeUnit.MILLISECONDS)
.until(new Predicate<WebElement>() {
@Override
public boolean apply(WebElement element) {
return element.getText().endsWith("04");
}
});
}
WebDriverWait示例:
public void exampleOfWebDriverWait() {
WebElement foo = driver.findElement(By.id("foo"));
new WebDriverWait(driver, 10)
.pollingEvery(2, TimeUnit.SECONDS)
.withTimeout(10, TimeUnit.SECONDS)
.until(ExpectedConditions.visibilityOf(foo));
}