Wait Command in Selenium Webdriver | Implicit Wait, Explicit Wait and FluentWait in Selenium

Some websites take time to load. You might be required to test them for page elements loading issues. That’s where Wait command in Selenium Webdriver comes into picture.

People just hate waiting. If the said website doesn’t open in more than 5 to 10 seconds, there are chances that they will move on to a better application or website.

Also, websites that take a lot of time to load tend to lose traffic. It isn’t a good sign of a strong build. Hence, clients and owners often ask you to give that parameter a proper precedence.

Page Load Timeout

We can test pages for load timeouts using a simple pageLoadTimeout method available in the driver.manage().timeouts() method. Using the pageLoadTimeout method we can provide some time for the page to load after which if it doesn’t load, it will throw an error or exception. Based on this very criteria you can create a test case on the lines of:

If page doesn’t load in 10 seconds, fail.

We will see a simple example where I will deliberately enter a value that will fail our test.

Let’s take the example that we were checking out in the Webdriver chapter.

Right before we were using the get method to navigate to our website, we will make use of the pageLoadTimeout method.

pageLoadTimeout method in Selenium

Type the following code right before the driver.get() method:

driver.manage().timeouts().pageLoadTimeout(long arg0, TimeUnit arg1);

As you can see in the above picture, the moment we pressed . (dot) after timeouts() it automatically flares up some suggestions. The method that we need is pageLoadTimeout(long arg0, TimeUnit arg1) which requires two parameters. The first one is supposed to be the time you wish to enter while the second parameter specifies the format you wish to use.

Example for Page Load Timeout

Let’s put just 1 second in the first parameter and TimeUnit.SECONDS in the second.

driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.SECONDS);

Since we are making use of TimeUnit class it is mandatory to import the following package:

import java.util.concurrent.TimeUnit;

If you are working on Eclipse don’t worry it will automatically import the aforementioned bit.

Our code will appear something like this now:

page load timeout example in selenium Webdriver

So let’s run this.

There! The website failed to load in 1 second, and hence an error was flung like this:

error message for page load timeout

We use the page Load Timeout method when we are dealing with web pages. For web elements, you can make use of some other crucial wait commands in Selenium Webdriver that we are going to see next.

Types of Wait Command in Selenium Webdriver for Web Elements

Nowadays websites are being designed using Javascript, Ajax etc. Then some use different plugins to load a particular element and they flare up only when you are scrolling down. Each web element nowadays takes different time to load.  Some web elements fail to load in a prescribed time which isn’t good for business. For that, any website owner would want their web elements to load in a given time. That’s where wait command in Selenium Webdriver for Web Elements come in handy.

So the concept here is we need to provide some timeout value as a parameter under which the web element should load. If it doesn’t, an exception will be thrown.

There are three types of waits that you can use in Selenium Webdriver when you are dealing with Web Elements . They are:

  1. Implicit Wait
  2. Explicit Wait
  3. Fluent Wait

Each one of them serves a specific purpose, the reason why they are a tad different from each other. However, using them we mainly accomplish the same thing that is allowing our program to wait, allowing web elements to load.

We will understand the whole concept of waiting, how we can use the wait command in Selenium Webdriver effectively with the help of examples in the following section.

waiting meme for wait command in selenium webdriver

Oh you are already waiting?

Implicit Wait Command in Selenium Webdriver

Implicit Wait is applicable for all web elements that are on a web page. If any element is not available within the specified time, it will throw a NoSuchElementException but it will always, and always look for that element for the specified period.

It holds true for all web elements on the page. So in a way, you can call it a global wait. It will check for element presence and wait for it to show for the timeout interval you enter, and will only move forward if that element is found within that time limit or an exception is encountered. Implicit wait timeout is 0 by default.

In order to use implicit wait, you need to type the following line in your code.

driver.manage().timeouts().implicitlyWait(long arg0, TimeUnit arg1);

Remember it has to be used just once in your code. No need to keep writing the code like you used to when you used Thread.sleep() to wait for an element.

UPDATED: In Selenium 4, the above is deprecated. You can use this instead:

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

Example of Implicit Wait in Selenium

Go ahead and type the aforementioned syntax in your code. Right after the website is successfully loaded. Look for an element on the page. I am going to search the search box which has the name as ‘s’.

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;

public class WebDriverDemo {
 public static void main(String[] args) { 
            ChromeDriver driver = new ChromeDriver(); 
            driver.get("http://dumbitdude.com"); 
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 
            driver.findElementByName("s"); 
            System.out.println(driver.getTitle()); 
            driver.quit();
      }
}

As you can see even here you need to import the TimeUnit package:

import java.util.concurrent.TimeUnit;

I have provided the implicit wait as 10 seconds in the aforementioned code. It will wait for the web element to load for 10 seconds but if within 10 seconds it finds it, it will load it anyway. So it’s not like it will always wait 10 seconds each time it has something to load.

Let’s put a non-working bit in the aforementioned code. Let’s search for something which is not there.

Failing the Test

Replace the findElementByName code by a value that is bound to fail like this:

driver.findElementByName("q");

There’s no element on the page that goes by the name “q”. Hence we are definitely going to get an exception. This is to show you that Selenium Webdriver will run for a whole 10 seconds after which only it will give the exception or error.

So our whole code will now appear something like this:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;

public class WebDriverDemo {
 public static void main(String[] args) { 
        ChromeDriver driver = new ChromeDriver(); 
        driver.get("http://dumbitdude.com"); 
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);        
        driver.findElementByName("q"); 
        System.out.println(driver.getTitle()); driver.quit();
     }
}

Now if you will run the code, you will see the website will load nevertheless:

website opens nevertheless

But it will wait for 10 seconds to find the element “q” on the page. When it fails to find it, it will release an exception message:

uncreachable code

It is worth noting that the next line code which was about grabbing the title, failed to execute. Because it never made it there.

Pretty cool huh!

Hold that thought!

Explicit Wait Command in Selenium Webdriver

The primal limitation of implicit wait is the fact that it only checks for the presence of web elements. That’s it!

To tackle with the shortcomings of Implicit Wait you can make use of Explicit Wait. Remember you can use both implicit and explicit wait at the same time or them individually. No issues there!

With Explicit wait command in Selenium Webdriver, you can layer your waiting period with certain conditions. Until those conditions are met, the waiting will keep happening, and the control will not go to the next statement.

There is this ExpectedConditions class which retains some predefined conditions that you can use to guarantee a proper waiting duration until your element is loaded. That way you can curtail the individual element loading issues.

ExpectedConditions Class methods

ExpectedConditions class has all sorts of combinations and methods that you could possibly use while working on your test scenarios. You can browse through all the methods by using the following link:

ExpectedConditions Methods

It is perfect for scenarios wherein websites make use of Ajax to load dynamic info.

When you are supposed to wait for an alert message, a button or a value to show up after some time on a page, Explicit Wait Command in Selenium Webdriver is the ideal waiting command to opt for.

Syntax of Explicit Wait

The syntax to remember here is:

WebDriverWait wait = new WebDriverWait(WebDriver driver, long timeOutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpathInfo"));

Where the first line should specify the driver object you wish to work upon with time in seconds. The second line will change depending upon the condition you wish to apply for. Also, you could replace xpathInfo with whatever the Xpath of the concerned element is. You can also choose to search an element by using any of the other locators.

Since we are making use of ExpectedConditions and WebDriverWait class here, you need to import the following packages:

import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

Let’s take a look at an example that deals with visibility of a Web Element. We will visit the website “http://dumbitdude.com” and then try to wait for the tab element “How to Add Social Media Links to Youtube Channel” to show, and then click on it.

Example for Explicit Wait Command in Selenium Webdriver

Type the following code in your Eclipse IDE:

import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class WebDriverDemo {
      public static void main(String[] args) { 
                 ChromeDriver driver = new ChromeDriver(); 
                 driver.get("http://dumbitdude.com"); 
                 WebDriverWait wait = new WebDriverWait(driver,10); 
                 wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("tab-item-title"))).click(); 
                 System.out.println("Element was clicked"); 
                 driver.quit();
           }
}

If you run the above program you will notice Google Chrome opening the website mentioned. Then it will wait for the Web Element to show by searching it using its class name which is “tab-item-title” here. Once it locates it, it will simply click on it.

You will be redirected to the following page:

how to add page in dumb it dude
console message displayed

And the system out message Element was clicked will begin to display in the console like this:

Here you can catch TimeOutException to handle timeout issues.

There are tons of other ExpectedConditions that you can explore.

For e.g. there is another one that looks for the “presence of element” on the page. So if there is some element the presence of which you are testing on a web page, you can make use of presenceOfElementLocated condition to test it.

Then there is alertIsPresent condition which is great when you are looking for an alert message to be displayed.

FluentWait in Selenium Webdriver

Fluent Wait is similar to Explicit Wait only. The difference being, it lets you create your own conditions, unlike Explicit Wait that used to come with its own predefined conditions.

FluentWait in Selenium is part of the org.openqa.selenium.support.ui pacakage. So you know which package to import while working with it.

It implements Wait Interface.

Here we have a concept called polling, which is nothing but a repetitive visitation of your condition to ensure whether it is met or not. By default, the polling period is set to 250 milliseconds which means your condition will be checked every 250 ms by default. You can change the time to suit your test case.

We can choose to ignore exceptions too using Fluent Wait which is another plus point of using it.

Here’s the syntax to be used:

Wait wait = new FluentWait(Webdriver driver)
.withTimeout(timeout, SECONDS)
.pollingEvery(timeout, SECONDS)
.ignoring(Exception.class)

The syntax is pretty self-explanatory. You just have to provide the respective Timeout values and specify how often you wish polling to happen and then eventually provide the name of the exception class that you wish to ignore.

Example of Fluent Wait Command in Selenium Webdriver

When you are creating an object of FluentWait you could specify an input. You can choose to not include it, it will just give you a warning of FluentWait being a raw type.

FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);

NOTE: Since Wait is an interface we can make use of the implementing FluentWait class directly in the code.

Time to use polling now. You will notice the moment you start typing wait.polling it will automatically give the following suggestion in Eclipse:

polling every code in eclipse

Just use the syntax from here and type the following code:

wait.pollingEvery(1, TimeUnit.SECONDS);

It means that it will poll every 1 second to check the condition you have specified.

You can choose to provide timeout period as well. For that just type the following in your code. I am going to provide a 30 seconds timeout:

wait.withTimeout(30, TimeUnit.SECONDS);

If there’s an exception that you wish to ignore you can make use of the following:

wait.ignoring(Throwable.class);

I have ignored the base exception Throwable.

We aren’t done yet. Where’s our condition?

Adding your Own Custom Condition

The condition herein will be a tad different from Expected Conditions that we had seen in Explicit.

Here you have to create your own condition. You can do so by making use of the Functions Interface which takes two parameters. The first one is input, while the second one is output.

Here’s the code you need to add:

wait.until(new Function<WebDriver, WebElement>(){

});

If you don’t understand the way this syntax ends, you can check out our Anonymous Inner Classes Tutorial.

Since Function wouldn’t be recognized by Eclipse just navigate to Function interface and select the first option that says google.common.base:

import from google common base

it will import the following package:

import com.google.common.base.Function;

However, with the inclusion of the above, the errors wouldn’t leave. Just navigate to the Function interface again, and it will suggest you to use its unimplemented methods:

unimplemented methods of Function Interface

Just click on the Add unimplemented methods link and it will add an apply method in your existing code:

wait.until(new Function<WebDriver,WebElement>(){

              @Override public WebElement apply(WebDriver arg0) { 

                    return null;
               }   

});

The method should receive the condition you wish to check for. You can make use of your own set of conditions to verify something on a page. It’s all up to you.

You can choose to use your own parameter in place of arg0.

An Example to Depict FluentWait

So our whole code will look something like this:

wait.until(new Function<WebDriver,WebElement>(){
         @Override public WebElement apply(WebDriver ld) {
                   WebElement element = ld.findElement(By.className("tab-item-title")); 
                   String s = element.getText();
                   if(s.equalsIgnoreCase("How to Add Social Media Links to Youtube Channel")) {
                        System.out.println("Element Found"); 
                        return element; 
                    } else { 
                       System.out.println("Element not present"); 
                       return null; 
                    } 
          } 
});

If you run the above it will give you the following result:

Element Found

Although the above example isn’t a good one, since there was no counter involved, it serves the purpose still and gives you an idea that you could use your very own conditions in the apply method box.

Alright! Now that you know all kinds of wait command in Selenium Webdriver it is time to start using them.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

Leave a Reply