流畅等待执行什么操作?
javascriptdom更新于 2026/1/28 12:28:17
流畅等待是一种动态等待,它使驱动程序暂停以在抛出异常之前以一定频率检查的条件。在 DOM 中搜索元素不是持续的,而是以固定的时间间隔搜索。
例如,如果等待时间为 5 秒,FluentWait 会定期监视 DOM(通过在时间内轮询定义)。在 FluentWait 中,需要构建基于条件的自定义等待方法。
语法 −
Wait<WebDriver> w = new FluentWait< WebDriver >(driver) .withTimeout (10, SECONDS) .pollingEvery (2, SECONDS) .ignoring (NoSuchElementException.class)
示例
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.FluentWait;
public class Fluentwt {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://www.tutorialspoint.com/index.htm";
driver.get(url);
//对每个元素应用隐式等待时间(以秒为单位)
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
//单击 Coding Ground 链接
driver.findElement(By.xpath("//span[text()=’Coding Ground’]")).click();
// 流畅等待声明
Wait<WebDriver> w = new FluentWait<WebDriver>(driver).withTimeout
(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(3)).ignoring(
NoSuchElementException.class);
WebElement fl = w.until(new Function<WebDriver, WebElement>() {
// 自定义流畅等待条件
public WebElement apply(WebDriver driver) {
if (driver.findElement(By.xpath("[//img[@title=’Whiteboard’"))
.isDisplayed()) {
return true;
}else {
return null;
}
}
});
driver.quit();
}
}
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

