selenium - 需要帮助理解流畅的等待Java代码
问题描述
我正在尝试理解与 Selenium 中的 fluent Wait 相关的 Java 代码。代码如下:
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
我知道整个代码正在等待直到方法返回特定的 WebElement。但我的疑问与下面的代码片段有关。
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
}
我也了解 Function 是一个内置的功能接口,它将 WebDriver 作为输入并返回 WebElement 作为输出。但是new关键字如何适合整个代码呢?
解决方案
Fluent Wait 使用两个参数——超时值和轮询频率。
1.等待条件的最长时间
2.检查指定条件成功或失败的频率。
此外,如果您想将等待配置为忽略诸如 之类的异常,则可以将其添加到 Fluent Wait 命令语法中。
Wait wait = new FluentWait(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
分析上面的示例代码。
1. Fluent Wait 以捕获开始时间来确定延迟开始。
2. Fluent Wait 然后检查 until() 方法中定义的条件。
3.如果条件失败,Fluent Wait 让应用程序按照pollingEvery(5, SECONDS)
方法调用设置的值等待。在此示例中,为 5 秒。
4.在步骤 3 中定义的等待期满后,将根据当前时间检查开始时间。如果等待开始时间(步骤1中设置)与当前时间的差小于withTimeout(30, SECONDS
)方法中设置的时间,则需要重复步骤2。
上述步骤将重复执行,直到超时到期或条件变为真。
函数是函数接口
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
/**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
推荐阅读
- asp.net-core-mvc - Azure Web 应用找不到 .NET Core 2.1 应用的视图
- angular - 从 express 向 mongoDB 发布请求
- javascript - 从 Node.js 调用 VBScript
- c# - 将实体添加到上下文时将 GUID 保留为空
- python - 我无法绘制多灰度图像
- java - 如何使用特定的运行时参数运行 jar 文件
- php - Drupal 7 最近的日志消息
- javascript - 使用 Web-Bluetooth 的蓝牙设备的信号强度
- sql - 第 2 部分:如何在不实际旋转的情况下获取基于分区的查询的总和
- google-apps-script - 您如何从 Google Drive 中的文件所在的文件夹获取在 Google Sheets 中显示的文件夹