What are the types of Selenium Waits for page load?

Can anyone please help mewith my research on the types of Selenium Waits for page load.

1 Like

Selenium waits for page load play an important part in your Selenium scripts. They help to make them less flaky and more reliable. Selenium provides multiple waits to provide adequate wait or pause in your script execution based on certain conditions. Thereby ensuring you donā€™t end up getting failed scripts as you perform automation testing with Selenium.

Although, which Selenium wait type is best?

Well, that is one question which is often encountered by budding automation testers. To understand the answer we first need to understand different types of Selenium.

Types of Selenium Waits For Page Load

When performing automation testing with Selenium, we use the following types of waits as we generate our Selenium script:

  • Thread.Sleep() method
  • Implicit Wait
  • Explicit Wait
  • Fluent Wait

Let us understand each one of these in-depth.

Thread.Sleep() For Automation Testing with Selenium

Sleep is a static method that belongs to the thread class. This method can be called using the reference of the class name i.e Thread. If you use Thread.sleep while performing automation testing with Selenium, then this method will stop the execution of the script for the specified duration of time, irrespective of whether the element is found or not on the web page. It accepts the time duration in milliseconds. The syntax for the same is:

Thread.sleep(3000);

The sleep function throws InterruptedException so it should be handled using a try-catch block as below:

try{ Thread.sleep(5000); } catch(InterruptedException ie){ }

Why Using Thread.Sleep() Is Not A Good Idea?

I will now be highlighting some disadvantages of using the thread.sleep().

  • Selenium Webdriver waits for the specified time, irrespective of the element is found or not. In case the element is found much before the specified duration, the script will still wait for the time duration to elapse, thereby increasing the execution time of the script.

  • If the element to be present does not appear after a static time and keep changing, then you will never know an estimated time needed for the sleep function. In case it takes more time than the defined time, the script shall throw an error. Which is why, if you are dealing with dynamic elements using Selenium waits then it is wise to not use Thread.sleep().

  • Thread.sleep is intended only for the element it is written prior to. In case you have two to fours elements which need to wait for a certain duration to load, you need to specify Thread.sleep as many times in that case. And if you do that! Well, you will find your script filled with Thread.sleep() syntax all over the place.

Owing to the above disadvantages, using Thread.Sleep() in your script creation is considered as a bad practice.

Implicit Wait For Automation Testing with Selenium

Selenium has overcome the problems provided by Thread.sleep() and have come up with two Selenium waits for page load. One of which is Implicit wait which allows you to halt the WebDriver for a particular period of time until the WebDriver locates a desired element on the web page.

The key point to note here is, unlike Thread.sleep(), it does not wait for the complete duration of time. In case it finds the element before the duration specified, it moves on to the next line of code execution, thereby reducing the time of script execution. This is why Implicit wait is also referred to as dynamic wait. If it does not find the element in the specified duration, it throws ElementNotVisibleException.

Another interesting thing to note about Implicit wait is that it is applied globally, which makes it a better option than Thread.sleep(). Meaning you only need to write it one time and it gets applicable for all of the web elements specified on a script throughout the WebDriver instance. Convenient isnā€™t it? The syntax to achieve the same is:

driver.manage().timeouts().implicitlyWait(Time Interval to wait for, TimeUnit.SECONDS);

The default time for Implicit wait is zero and it keeps polling for the required element after every 500 milliseconds. Letā€™s see the code snippet below, showcasing the use of Implicit wait. In this example, I am using the same easemytrip example. In this case, we are going a step ahead and continuing the booking process, where the page takes more time to load. Here the page load issue exists for two pages, which we are dealing using a single line of code using implicit wait rather than using Thread.sleep() multiple times.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select;

import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptExecutor;

public class ImplicitWait {

public static void main(String[] args) throws InterruptedException {
    // TODO Auto-generated method stub
    
    //setting the driver executable
    System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");
    
    //Initiating your chromedriver
    WebDriver driver=new ChromeDriver();
    
    driver.manage().window().maximize();
    
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.get("https://www.easemytrip.com/");
    
    driver.findElement(By.id("FromSector_show")).sendKeys("Delhi", Keys.ENTER);
    driver.findElement(By.id("Editbox13_show")).sendKeys("Mumbai", Keys.ENTER);
    driver.findElement(By.id("ddate")).click();
    driver.findElement(By.id("snd_4_08/08/2019")).click();
    driver.findElement(By.className("src_btn")).click();

    driver.findElement(By.xpath("//button[text()='Book Now']")).click();
    
    JavascriptExecutor jse = (JavascriptExecutor)driver;
    jse.executeScript("window.scrollBy(0,750)");
    
    driver.findElement(By.xpath("//input[@type='email']")).sendKeys("sadhvisingh9049@gmail.com");
    
    driver.findElement(By.xpath("//span[text()='Continue Booking']")).click();
    
    WebElement title=driver.findElement(By.id("titleAdult0"));
    
    Select titleTraveller=new Select(title);
    
    titleTraveller.selectByVisibleText("MS");
    driver.findElement(By.xpath("//input[@placeholder='Enter First Name']")).sendKeys("Sadhvi");
    driver.findElement(By.xpath("//input[@placeholder='Enter Last Name']")).sendKeys("Singh");
    
    driver.findElement(By.xpath("//input[@placeholder='Mobile Number']")).sendKeys("9958468819");
    
    driver.findElement(By.xpath("//div[@class='con1']/span[@class='co1']")).click();
    

}

}

Now, here we are aware of the fact, that pages shall we loaded in a certain duration, but what if we do not know the element to be visible/clickable at loading time. As in the time of its appearance is dynamic and keeps on changing from time to time. In this case, Explicit wait will help you overcome this problem.

Explicit Wait For Automation Testing with Selenium

The Explicit wait is another one of the dynamic Selenium waits. Explicit wait help to stop the execution of the script based on a certain condition for a specified amount of time. Once the time goes overboard, you will get the ElementNotVisibleException. In a scenario where you do not know the amount of time to wait for, this explicit wait comes in handy. Using conditions like elementToBeClickable() or textToBePresentInElement(), one can wait for the specified duration. One can use these predefined methods using the combination of classes WebDriverWait and ExpectedConditions.

Types of Expected Conditions:

Below are the few types of expected conditions commonly used as you perform automation testing with Selenium.

  • visibilityOfElementLocated()- Verifies if the given element is present or not

  • alertIsPresent()- Verifies if the alert is present or not.

  • elementToBeClickable()- Verifies if the given element is present/clickable on the screen

  • textToBePresentInElement()- Verifies the given element have the required text or not

  • titlels()- Verify the condition wait for a page that has a given title

Below is the code snippet highlighting the usage of an Explicit Selenium wait. In this example, we are using the ā€˜rentomojoā€™ application, where a modal appears at a dynamic time on the homepage. Using explicit wait, based on the element visibility, we will wait for the element and close the pop-up. Referenced code:

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; 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) {
    // TODO Auto-generated method stub
    
    //setting the driver executable
            System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");
            
            //Initiating your chromedriver
            WebDriver driver=new ChromeDriver();
            
            
            
            driver.manage().window().maximize();
            
            driver.get("https://www.rentomojo.com/");
            
            driver.findElement(By.xpath("//span[@class='rm-city__selectorBoxLoca'][contains(text(),'Delhi')]")).click();
            
            
            
            WebDriverWait wait=new WebDriverWait(driver, 120);
            
            
            wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//div[@class='Campaign__innerWrapper']/button"))));
            driver.findElement(By.xpath("//div[@class='Campaign__innerWrapper']/button")).click();

}

}

Note- When implicit wait and explicit wait are given in conjunction, then they work on cumulative time, rather than on a single wait condition. For example, if the Implicit wait is given for 30 seconds and the Explicit wait is given for 10 seconds, then the explicit element it is looking for will wait for 40 seconds.

The Difference Between Selenium Waits: Explicit Vs Implicit

Now, since you are aware of the usage of implicit and explicit waits, let us investigate the difference between these 2 Selenium waits:

IMPLICIT WAIT

  • It is by default applied to all the elements in the script.

  • We cannot wait based on a specified condition like element selectable/clickable unlike explicit .

  • It is usually used when you are sure the element may be visible in a certain time

EXPLICIT WAIT

  • It is applicable to only a certain element which is specific to a certain condition.
  • In explicit, we can specify the wait based on a specific condition.
  • It is usually used when you are not aware of the time of the element visibility. It is subjected to dynamic nature.

**** Fluent Wait For Automation Testing with Selenium****

The Fluent wait is similar to explicit wait in terms of its functioning. In Fluent wait, you perform a Selenium wait for an element when you are not aware of the time it may take to be visible or clickable. The few differential factors that Fluent wait offers are:

  • The polling frequency- In case of Explicit wait, this polling frequency is by default 500 milliseconds. Using Fluent wait, you can change this polling frequency based on your needs, i.e you can tell your script to keep checking on an element after every ā€˜xā€™ seconds.

  • Ignore Exception- During polling, in case you do not find an element, you can ignore any exception like ā€˜NoSuchElementā€™ exception etc.

Apart from these differential factors, like Explicit wait or Implicit wait, you can define the amount of time to wait for the element to be visible or actionable. The below syntax or lines of code are used to define Fluent wait in Selenium:

Wait fluentWait = new FluentWait(driver) .withTimeout(60, SECONDS) // this defines the total amount of time to wait for .pollingEvery(2, SECONDS) // this defines the polling frequency .ignoring(NoSuchElementException.class); // this defines the exception to ignore WebElement foo = fluentWait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) //in this method defined your own subjected conditions for which we need to wait for { return driver.findElement(By.id(ā€œfooā€)); }});

My opinion on Fluent Selenium Wait?

I personally havenā€™t found any useful implementation of fluent wait in a real-time example, hence would like to refrain myself from the implementation of it, as of now. I am as eager as you, for the launch of Selenium 4. I am hoping that after the launch we may get more insights on the practical advantage of using Fluent wait over the other Selenium waits. So far based on my experience, I happen to lean towards the use of Explicit Selenium wait, owing to its easier implementation of code than Fluent Selenium wait.

Read More: Selenium Waits: Implicit, Explicit, Fluent And Sleep