การรออย่างคล่องแคล่วเป็นการรอแบบไดนามิกซึ่งทำให้คนขับหยุดชั่วคราวสำหรับเงื่อนไขที่มีการตรวจสอบความถี่ก่อนที่จะส่งข้อยกเว้น มีการค้นหาองค์ประกอบใน 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);
//implicit wait with time in seconds applied to each elements
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
//Clicking on Coding Ground link
driver.findElement(By.xpath("//span[text()=’Coding Ground’]")).click();
// fluent wait declaration
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>() {
// customized condition for fluent wait
public WebElement apply(WebDriver driver) {
if (driver.findElement(By.xpath("[//img[@title=’Whiteboard’"))
.isDisplayed()) {
return true;
}else {
return null;
}
}
});
driver.quit();
}
}