Selenium WebDriver: Waits for Test Automation (Timeouts, Threads.sleep, Explicit Wait, Implicit Wait & Fluent Wait)

Diyorbek Mamadaliev
7 min readNov 12, 2023

Content

  • Selenium Timeouts
  • Threads.sleep()
  • Explicit Wait
  • Implicit Wait
  • Fluent Wait

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.

Proper “wait” methods are always implemented in WebdriverWait or ExpectedConditions

Selenium Timeouts (Sync issues solution)

In Selenium, a TimeoutException is an exception raised when an operation runs out after a specified period. For example, when using the WebDriver.get method to load a page, the default timeout is set to 30 seconds. If the page takes longer than 30 seconds to load, a TimeoutException will be raised.

Default Selenium Timeouts:

Implicit Wait

  • 0 seconds for implicit waits. Here the Selenium Command reports immediately if it cannot find an element.

Page Load

  • 300 seconds for page loads

Script Load

  • 30 seconds for script timeouts

How does Selenium handle connection timeout?

In Selenium, you can handle a connection timeout by setting a timeout value for the WebDriver using the set_page_load_timeout() method. This method sets the maximum time (in seconds) that the driver should wait for a page to load before throwing a TimeoutException. For example to set timeout as 10 seconds, you can use set_page_load_timeout(10)

How long is Selenium timeout?

The timeout in Selenium is set in seconds or milliseconds, depending on the method used. For example, the set_page_load_timeout() method in the WebDriver takes the timeout value in seconds, while the pause command in Selenium IDE takes the timeout value in milliseconds.

You can change the default timeout in Selenium by using the

set_page_load_timeout method of the WebDriver object. For example:

driver.set_page_load_timeout(10)

You can also set a timeout for implicitly waiting for an element to be present on the page, using the implicitly_waitmethod.

If a session runs for more than 7200 seconds (2 hours), the session is stopped, changing the status to TIMEOUT on the dashboard.

Thread.sleep()

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){

}

Used when we need to:

  • Detect sync issues
  • Count some time independently of application state or test flow
  • Freeze all java processes to see something in Debug mode

Explicit Wait

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. In order to use this case, import the below packages in your class:

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

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

Post this one needs to create a reference variable for the WebDriverWait class and instantiate it using the WebDriver instance and providing the amount of Selenium wait for page load, one may need. The unit of time is in seconds. One can define it as below:

WebDriverWait wait = new WebDriverWait(driver,30);

In order to use the predefined methods of the ExpectedCondition Class, we will use the wait reference variable as below:

wait.until(ExpectedConditions.visibilityOfElementLocated(Reference of Element to be  located using locator));**Types of Expected Conditions:**

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

There are many more expected conditions available, which you can refer through the Selenium official GitHub page. Like Implicit wait, the explicit wait also keeps polling after every 500 milliseconds.

Below is the code snippet highlighting the usage of an Explicit Selenium wait.

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) {

System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");
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

Implicit Wait

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:

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 {
System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");
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();

}

}

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

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<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)

.withTimeout(60, SECONDS)

.pollingEvery(2, SECONDS)

.ignoring(NoSuchElementException.class);

WebElement foo = fluentWait.until(new Function<WebDriver, WebElement>() {

public WebElement apply(WebDriver driver)

{ return driver.findElement(By.id("foo"));

}});

the major difference between the Explicit wait and the Fluent wait is, that the Explicit Selenium Wait provides predefined conditions, which are applied on elements we need to wait for, whereas, in case of Fluent Selenium wait, you can define your own customized conditions within the apply method.

--

--

Diyorbek Mamadaliev

Software Engineer aspiring to be a Research Computer Scientist. I dive into software, testing, robotics, and connect with like-minded folks.