在Selenium中使用Fluent Wait时,设置超时和轮询频率的方法如下:
设置超时(Timeout)
超时是指等待某个条件成立的最大时间。在Fluent Wait中,可以通过withTimeout
方法来设置超时时间。例如,如果你想设置超时时间为30秒,可以这样写:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30L)); // 设置超时时间为30秒
这里Duration.ofSeconds(30L)
表示等待时间为30秒,L
表示长整型(long)。
设置轮询频率(Polling Interval)
轮询频率是指检查条件是否满足的频率。在Fluent Wait中,可以通过pollingEvery
方法来设置轮询频率。例如,如果你想设置每5秒检查一次,可以这样写:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.pollingEvery(Duration.ofSeconds(5L)); // 设置轮询频率为每5秒
这里Duration.ofSeconds(5L)
表示轮询间隔为5秒。
示例代码
结合上述设置,以下是一个完整的示例,展示了如何设置超时和轮询频率,并使用Fluent Wait等待某个元素出现:
//实例:https://www.fenza.cn/
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30L)) // 设置超时时间为30秒
.pollingEvery(Duration.ofSeconds(5L)) // 设置轮询频率为每5秒
.ignoring(NoSuchElementException.class); // 忽略NoSuchElementException异常
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
在这个示例中,我们等待最多30秒,每5秒检查一次,直到找到ID为"foo"的元素或者超时