Selenium Wait Commands – Implicit, Explicit, Fluent Waits

Selenium Wait Commands: When we discussed how to write the first Java Selenium automation script, you may have seen the wait statements in those programs. But in this, we will discuss those wait statements and different types with real-time examples. In this post, we are going to cover:

What are Selenium Wait Commands?

These wait statements are one of the important statements of the automation script because they help users to fix or know the issue before re-directing to a new web page; as we know, a web application can be developed using different technologies like JavaScript and Ajax, so some of the elements are loaded a little bit late so in that case, these wait statements help to wait for some time so that those elements are available in the browser and we can interact with them also.

Why Do We Need Waits In Selenium?

As the selenium script execution is very fast, the default wait time duration is 0(Zero), so when we are running our script, then that time may be the application is loaded completely, or it may be in loading only. So, if the element is not loaded, our automation script will throw an “ElementNotVisibleException” exception. But with the help of wait statements, we can fix such problems.

Now, let’s know the different types of wait statements in Selenium WebDriver. In Selenium, three different wait statements or commands are present:

Implicit Wait Type
Fluent Wait Type
Explicit Wait Type
Selenium Wait Commands
Selenium Wait Commands

Implicit Wait

This Implicit Wait idea is mainly borrowed from the Waitr. With the help of Implicit Wait, we are told to the WebDriver to wait for the specified amount of time before. If the element is not located within that interval, then WebDriver will throw an “ElementNotVisibleException”.

Notes: If you have used the implicit wait statements, then the time interval is applied for all the elements, and it’s valid until the browser is open.

The syntax for the implicit wait looks like this:

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

Code Snippet

package com.selenium.practice.waits;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ImplicitWait 
{
   public static void main(String[] args) throws InterruptedException 
   {
      WebDriver driver;
      System.setProperty("webdriver.chrome.driver","Path Of Browser Driver");

      driver=new ChromeDriver();
      driver.manage().window().maximize();
      //Implicit Wait - Here the specified Implicit Wait time frame is 15 seconds.
      //It waits 15 seconds of time frame for the element to load. 
      //It throws an exception, if the element is not loaded within the specified time frame
      driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);

      driver.get("https://softwaretestingo.blogspot.com/");
      driver.close();	
   }
}

Note 1: Implicit, Explicit, and Fluent waits are dynamic waits. What are dynamic waits? Consider a situation where you have given a TimeOut value of 20 seconds. If the element is loaded in 5 seconds, the rest 15 seconds will be ignored. It won’t wait until the TimeOut value is completed, i.e., 20 seconds. That’s why all waits are considered dynamic waits.

Note 2: Implicitly wait is applied globally, which means it is always available for all the web elements throughout the driver instance. It implies that if the driver interacts with 100 elements, then implicitly wait is applicable for all the 100 elements.

This is easy to apply, but it also introduces a few drawbacks. Because the time interval is applicable for all the elements, the execution time also increased. So, to avoid such issues, Selenium WebDriver introduces another type of wait called Explicit wait.

Explicit Wait

This is a concept of dynamic waits that waits for some particular conditions. That means we can use such types of waits to pause the execution of our script until a specific time or condition is met. Unlike implicit wait, this Explicit wait applies to the particular element or instance. If it cannot locate the elements after waiting for that specified time, it will throw an “ElementNotVisibleException”.

To understand why we have explicit wait in selenium WebDriver and when we should use it in the selenium programs, we will try to know with a couple of examples.

Conditions For Explicit Wait in Selenium WebDriver

Suppose there is a login page, and the user is redirected to the dashboard page after success. So when it redirects the login page to the dashboard page, sometimes, it takes 10 seconds, and sometimes 20 seconds. So, in this situation, we can use explicit wait to wait until the specified page is absent.

Syntax:

WebDriverWait wait=new WebDriverWait(WebDriveReference,TimeOut);

In the above syntax, as you can see, we have created an instance or object of WebDriver wait, and in that, we have passed two parameters: driver reference and timeout.

Example Program:

package com.selenium.practice.waits;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ExplicitWait 
{
   public static void main(String[] args) throws InterruptedException 
   {
      WebDriver driver;
      System.setProperty("webdriver.chrome.driver","Path Of Browser Driver");

      driver=new ChromeDriver();
      WebDriverWait wait=new WebDriverWait(driver, 20000);
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(15000, TimeUnit.SECONDS);

      driver.get("https://softwaretestingo.blogspot.com/2020/08/how-to-use-explicit-wait-in-selenium.html");
      driver.findElement(By.xpath("//button[contains(text(),'Click me to start timer')]")).click();
      
      
      WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//p[text()='Automation Testing']")));
      Boolean status=element.isDisplayed();
      
      if(status)
      {
         System.out.println("Element Is Visible");
      }
      else
      {
         System.out.println("Element Not Visible");
      }
      driver.close();	
   }
}

At the time of using the explicit wait, we can use the below-expected condition:

alertIsPresent()
elementToBeClickable()
frameToBeAvaliableAndSwitchToIt()
invisibilityOfElementWithText()
presenceOfElementLocated()
textToBePresentInElementLocated()
titleIs()
visibilityOf()
visibilityOfAllElementsLocatedBy()
elementSelectionStateToBe()
elementToBeSelected()
invisibilityOfTheElementLocated()
presenceOfAllElementsLocatedBy()
textToBePresentInElement()
textToBePresentInElementValue()
titleContains()
visibilityOfAllElements()
visibilityOfElementLocated()

Implicit vs. Explicit Waits

Implicit WaitExplicit Wait
Applies to all elements in a test script.Applies only to specific elements as intended by the user.
In Implicit wait, we define a code to wait a certain amount of time to find an element or elements.In Explicit Wait, we write a code to define the wait statement for a specific condition to be satisfied until the wait reaches its timeout period.
There is no need to specify “ExpectedConditions” on the element to be locatedMust always specify “ExpectedConditions” on the element to be located
It is most effective when used in a test case in which the elements are located within the time frame specified in the implicit waitIt is most effective when the elements take a long time to load. Also useful for verifying the element’s properties, such as visibilityOfElementLocated, elementToBeClickable and elementToBeSelected
driver.manage().timeouts(). implicitWait(10,TimeUnit.SECONDS);WebElement element = wait.until (ExpectedConditions.elementToBeClickable(By.id(“someId”)));

Fluent Wait

The fluent wait is used to instruct the WebDriver to wait for a condition and also check the condition frequently within the specified time interval. And after the specified time interval, if the locator cannot locate the element, it will throw “ElementNotVisibleException”.

As we have discussed in explicit wait, if we have specified 20 seconds to wait for, it will wait until the specified time interval is completed. So, if the element is available in 5 seconds, we must wait 15 more seconds to execute the next statements. To overcome such a situation, we can use the fluent wait because it tries to find out the element in the different intervals (In each interval) until it finds the element or the time is over.

Syntax:

Wait wait = new FluentWait(WebDriver reference)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class);

Let us take an implementation of Fluent wait

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);

In the above statements, you can see that we have mentioned withTimeout is 30 seconds which means we are going to a maximum of 30 seconds at the same time, we have mentioned polling every 5 seconds, which means every 5 seconds to verify that the specified condition is a success or failure. Finally, we have directed WebdDiver to ignore NoSuchElementException if it occurs during the interval.

Selenium Fluent Wait Commands Example Program

package com.selenium.practice.waits;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;
public class FluentWaitExample 
{
   public static void main(String[] args) 
   {
      WebDriver driver;
      System.setProperty("webdriver.chrome.driver","Path Of Browser Driver");

      driver=new ChromeDriver();
      driver.manage().window().maximize();

      driver.get("https://softwaretestingo.blogspot.com/2020/08/fluent-wait-page-for-practice.html");
      driver.findElement(By.xpath("//button[contains(text(),'Click Me - Fluent Wait')]")).click();

      FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(30, TimeUnit.SECONDS)
            .pollingEvery(5, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);

      @SuppressWarnings("unused")
      WebElement element = wait.until(new Function<WebDriver, WebElement>()
      {

         @Override
         public WebElement apply(WebDriver driver) 
         {
            WebElement element = driver.findElement(By.xpath("//p[@id='demo']"));
            String getTextOnPage = element.getText();
               if(getTextOnPage.equals("Softwaretestingo - DEMO PAGE"))
               {
                  System.out.println(getTextOnPage);
                  return element;
               }
               else
               {
                  System.out.println("FluentWait Failed");
                  return null;
               }
         }
      });
      
      driver.close();
   }
}

While writing an automation script for your project, these three types of wait (implicit, explicit, and fluent wait) statements help us to solve the

Description

Synchronization errors. I hope with this Selenium WebDriver tutorial post, I can clear your doubts and give you a better understanding of this topic. You can comment in the comment section if you have any doubts.

What is pageLoadTimeout

Selenium defines different timeouts and different wait mechanisms. One of the timeouts is focused on the time a webpage needs to be loaded. the pageLoadTimeout limits the time the script allows for a web page to be displayed. If the page loads within the time, then the script continues. If the page does not load within the timeout, the script will be stopped by a TimeoutException.

How to set the timeout

The timeout is set at the driver level after creating the driver instance with the appropriate capabilities.

What is affected by the Timeout

This timeout setting will remain in force for the remainder of the script (until changed) and will affect any calls that generate a new web page. This includes the get() method in Java o. However, the timeout may be delayed until the first findElement() call for the new page since the navigation method may return asynchronously.

As a result, when using the timeout, webpage navigation should be executed under the control of try-catch clauses that catch the TimeoutException. For example:

//Define the timeout
RemoteWebDriver driver = new RemoteWebDriver(new
URL("https://" + host + "/nexperience/perfectomobile/wd/hub"), capabilities);
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
// Use the timeout when navigating to a webpage
try {
driver.get(myWebPage);
driver.findElementByXpath(verificationField);
} catch (TimeoutException e) {
System.out.println("Page: " + myWebPage + " did not load within 40 seconds!");
// treat the timeout as needed
}

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment