Most of the web applications are developed using Ajax and Javascript. When opening these applications, as a part of DOM the page loads first then the elements. When you find an element using any locator which is not yet loaded or available on the page then our code will throw exception saying unable to find the web element requested.
In order to solve the problem is to wait till the page loads, then look for those elements. By default we have a sleep method in Java which will halt the execution of our code till the time specified. In Selenium, we have two wait class which will not halt the code execution but wait till the element is loaded or till the timeout specified.
The Two types of waits are,
1. Implicit wait
2.Explicit wait
The Explicit wait can also be achieved in two ways,
1. WebDriver wait
2. Fluent wait
Fluent wait
This mechanism is little different when compared with Implicit and Explicit wait, fluent wait will be looking for the element requested at specific intervals. Thus avoid constant monitoring of web elements when you are aware that the requested element might take a particular time to load.
Fluent wait is least preferred when comparing other waits since they are complex to use and it will make the code complex to look
Syntax for Fluent wait
This syntax is available in selenium official page with all other available methods of fluent wait, check that from link here - Click to Open.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(30)) .pollingEvery(Duration.ofSeconds(3)).ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.xpath("//div[@id='start']//button"));
We will explain the syntax below
Code
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import java.time.Duration;
import java.util.function.Function;
import static java.util.concurrent.TimeUnit.SECONDS;
public class Fluent_wait {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","src\\Geko_driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://the-internet.herokuapp.com/dynamic_loading/1");
driver.findElement(By.xpath("//div[@id='start']//button")).click();
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(3)).ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.xpath("//div[@id='start']//button"));
}
});
}
}
Explanation
The