等待一个元素可以被编码为
WebElement foo = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("foo")));
在FluentWait,示例的文档不包括以下的超时,轮询间隔,异常忽略的定义给出。
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
两者有什么区别?任何额外的好处?
我搜索过的lambda表达式,功能接口。但我不太明白了。
WebDriverWait是FluentWait的使用webdriver的情况下,专业化。
该构造函数为:
WebDriverWait(WebDriver driver, java.time.Clock clock, Sleeper sleeper, long timeOutInSeconds, long sleepTimeOut)
WebDriverWait(WebDriver driver, long timeOutInSeconds)
:诱导这种等待会忽略所遇到的(抛出)默认情况下,在“直到”条件NotFoundException的情况,并立即传播所有其他人。WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis)
:诱导这种等待会忽略所遇到的(抛出)默认情况下,在“直到”条件NotFoundException的情况,并立即传播所有其他人。实施例A:
(new WebDriverWait(driver(), 5))
.until(new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver d) {
return d.findElement(By.linkText(""));
}
});
实施例B:
WebElement wer = new WebDriverWait(driver, 5).until((WebDriver dr1) -> dr1.findElement(By.id("q")));
实施例C:
(new WebDriverWait(driver(), 5)).until((driver) -> driver.findElement(By.linkText("Google")));
FluentWait是可以具有在飞行中配置其超时和轮询间隔Wait接口的实现。
每个FluentWait实例定义的最大时间量的等待条件,以及与检查条件的频率。此外,用户可以配置等待页面上的元素进行搜索时忽略特定类型的异常,而等待,如NoSuchElementExceptions。
用法示例:
// Waiting 30 seconds for an element to be present on the page, checking for its presence once every 500 milliseconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.name("q"));
}
});
注意:这个类是没有线程安全保证。
您可以在讨论Selenium Webdriver 3.0.1: Selenium showing error for FluentWait Class FluentWait的工作示例