When we try to test the presence of an element that may appear after every x seconds/minutes then comes the need of fluent wait. It tries to find the web element repeatedly at regular intervals(as specified in polling period) of time until the timeout or till the object gets found. It can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
WebElement ele = wait.until(new Function<WebDriver, WebElement>()
{
public WebElement apply(WebDriver driver)
{
WebElement element = driver.findElement(By.xpath("html/body/div[2]/div[4]/div[2]/div[1]/h1"));
String getTextOnPage = element.getText();
if(getTextOnPage.equals("Selenium Certification Training"))
{
System.out.println(getTextOnPage);
return element;
}
else
{
System.out.println("FluentWait Failed");
return null;
}}
});
Fluent Wait uses two parameters – timeout value and polling frequency. In the above syntax we took time out value as 30 seconds and polling frequency as 5 seconds. The maximum amount of time (30 seconds) to wait for a condition and the frequency (5 seconds) to check the success or failure of a specified condition. If the element is located within this time frame it will perform the operations else it will throw an “ElementNotVisibleException”. So, when we have web elements which sometimes visible in few seconds and some times take more time than usual (Ajax applications). We can set the default pooling period based on our requirement and also ignore any exception while polling an element.