在Selenium中使用Fluent Wait时,设置不同的等待条件主要通过以下几种方式实现:
1. 设置超时时间(withTimeout)
你可以使用withTimeout
方法来设置等待的最大时间。例如,如果你想设置最大等待时间为30秒,可以这样设置:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30)); // 设置超时时间为30秒
2. 设置轮询频率(pollingEvery)
使用pollingEvery
方法来设置检查条件的频率。例如,每5秒检查一次条件是否满足:
//实例: https://www.riben5.com/
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.pollingEvery(Duration.ofSeconds(5)); // 设置轮询频率为每5秒
3. 忽略特定异常(ignoring)
在等待过程中,你可能想要忽略某些异常,比如NoSuchElementException
。使用ignoring
方法来设置:
//实例:https://www.gs92.cn/
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.ignoring(NoSuchElementException.class); // 忽略NoSuchElementException异常
4. 自定义等待条件(until)
Fluent Wait允许你通过until
方法设置自定义的等待条件。你可以提供一个函数,当函数返回的值不为null
且为真时,结束等待:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
});
在这个示例中,until
方法接受一个Function<WebDriver, WebElement>
,该函数会在每次轮询时被调用,直到找到元素foo
或者超时。
通过这些方法,你可以灵活地设置Fluent Wait的不同等待条件,以适应各种复杂的测试场景。