等待元素可以编码为
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 表达式、函数式接口(interface)。但我不太明白。
最佳答案
WebDriver等待
WebDriverWait是使用 WebDriver 实例的 FluentWait 的特化。
构造函数是:
WebDriverWait(WebDriver 驱动程序、java.time.Clock 时钟、Sleeper sleeper、long timeOutInSeconds、long sleepTimeOut)
WebDriverWait(WebDriver driver, long timeOutInSeconds)
:引发此 Wait 将忽略 NotFoundException 的实例默认情况下在“until”条件下遇到(抛出)的,并立即传播所有其他条件。WebDriverWait(WebDriver driver, long timeOutInSeconds, long sleepInMillis)
:引发此 Wait 将忽略 NotFoundException 的实例默认情况下在“until”条件下遇到(抛出)的,并立即传播所有其他条件。
WebDriverWait 的 Lambda 实现
示例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 的实现可以动态配置超时和轮询间隔的接口(interface)。
每个 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"));
}
});
Note: This class makes no thread safety guarantees.
您可以在讨论 Selenium Webdriver 3.0.1: Selenium showing error for FluentWait Class 中找到 FluentWait 的工作示例
关于java - FluentWait 使用中使用 lambda 函数与不使用有何区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54551509/