Understanding Selenium Timeouts

Understanding Selenium Timeouts and learn how to Handle Timeout Exceptions in Selenium using Java & Python

Get Started free
Guide Banner Image
Home Guide Understanding Selenium Timeouts

Understanding Selenium Timeouts

Selenium is one of the most widely used tools for automation testing. Every command in Selenium Webdriver is an asynchronous operation.

Timeouts play a crucial role in web development and the developers work really hard to optimize the page load time. If the load time of a website is less it will load instantly and user experience would be high-quality, alternatively if it takes more time to load, users would lose interest and would swiftly slide into some other competitive websites.

This article focuses on how testers can set different timeouts in their test scripts using Selenium before it throws an exception.

What are Selenium Timeouts?

Selenium Timeouts are the longest periods of time for which a WebDriver should wait for specific actions or events to occur during a webpage interaction before it throws any error.

Consider a situation in which WebDriver fails to execute the test case as the webpage takes too long to load. In such cases, it is essential to mention the wait time for the page load to avoid test case failure. This is where Timeouts play an essential role. They are used to set an interval between actions performed on the test.

Timeouts are usually performed using Selenium wait commands.

The various Selenium Webdriver timeouts used while testing an application are as follows:

  • implicitlyWait()
  • setScriptTimeout()
  • pageLoadTimeout()

This article will explain how testers can set these timeouts with examples in Java and Python.

1. implicitlyWait()

Implicit Wait directs the Selenium WebDriver to wait for a certain measure of time before throwing an exception. Once this time is set, WebDriver will wait for the element before the exception occurs.

Once the command is run, Implicit Wait remains for the entire duration for which the browser is open. It’s default setting is 0, and the specific wait time needs to be set by the following protocol.

implicitlyWait() timeout is used to specify the time the driver should wait while searching for an element if it is not immediately present.

The syntax is as follows:

implicitlyWait(long time, java.util.concurrent.TimeUnit unit);
  • time – The amount of time to wait for
  • unit – The unit of measure for time

When searching for a particular single element, the driver should pause page loading until the element has been found. If it doesn’t wait, the timeout expires before throwing a NoSuchElementException.

When searching for multiple elements, the driver should pause the page until at least one element has been found or the timeout has expired.

Example:

implicitlyWait(20, TimeUnit.SECONDS);

In this statement, the WebDriver will wait for 20 seconds before proceeding to the next action.

Code Snippet:

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;

public class TimeoutExample {
public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver", "Path of Chrome Driver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.ebay.com/");

// Implicit wait timeout for 20seconds
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

driver.findElement(By.xpath("//input[@id='gh-ac']")).sendKeys("Mobile");

//xpath for search button
WebElement search = driver.findElement(By.xpath("//input[@id='gh-btn']"));

search.click();

}
}

On executing the code above, the driver will wait for 20 seconds on the particular website even if the web element is not found.

Note: If a user wants to increase the implicit wait timeout, it should be done carefully, as this will affect the test run time.

2. setScriptTimeout()

setScriptTimeout is a Selenium Timeout that specifies the time to wait for an asynchronous script to finish execution before throwing an error.

If the timeout is negative, not null, or greater than 2e16 – 1, an error code with invalid argument will be returned.

Syntax:

setScriptTimeout(long time,java.util.concurrent.TimeUnit unit);
  • time – The timeout value.
  • unit – The unit of time

The default timeout for setScriptTimeout method is zero. If you do not set time, then there are chances that executeAsyncScript method may fail because the JavaScript code may take more than the time allotted. To avoid such failures, set the setScriptTimeout. This is mainly used for Javascript objects and executors.

Example:

// setScriptTimeout for 10 seconds
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);
((JavascriptExecutor) driver).executeScript("alert('hello world');");
((JavascriptExecutor) driver).executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 500);");

In the example above, if the time is not used, then there will be an error stating: “Timed out waiting for async script result”. To avoid this error, one should use setScriptTimeout.

3. pageLoadTimeout in Selenium

PageLoadTimeout is a Selenium feature that specifies the maximum time that the WebDriver should wait for the page to render completely before throwing an exception.

When the user navigates to a new page or reloads the current page, WebDriver waits for the web page to load completely. If it fails to load within the specified timeout duration, it throws a Timeout exception.

This sets the time to wait for a page to load completely before throwing an error. If the timeout is negative, page loads can be indefinite.

Syntax:

pageLoadTimeout(long time,java.util.concurrent.TimeUnit unit);

This timeout is applicable only to driver.manage() and driver.navigate.to() methods.

Example:

public class PageLoadTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "Path of driver");
WebDriver driver = new ChromeDriver();
// set the time of 30 seconds for page to complete the loading

driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.get("https://www.google.com/");
}
}

In the code above, if your page does not load within 30 seconds, WebDriverException will be thrown.

Selenium Timeouts must be included to create effective, comprehensive and seamlessly running test cases. This article intends to help in this regard by briefly explaining how Timeouts work, and how they can be incorporated into Selenium test scripts.

To know more about Automation, refer to this piece on Selenium Automation.

Default Timeout in Selenium WebDriver

The default timeout depends on the type of wait command used.

  • Default Timeout for Implicit Wait is 0 seconds. Here the Selenium Command reports immediately if it cannot find an element.
  • Default Timeout for Page Load is 300 seconds.
  • Default Timeout for Script Timeout is 30 seconds.

How to handle a Timeout Exception in Selenium?

TimeOut Exception in Selenium mainly occurs when a given condition is not met in the specified time.

  • So one way to handle timeout exceptions is to adjust the wait time according to the application behavior so that the webpage is loaded completely and all web elements are visible.
  • We can also use polling, also called a fluent wait in selenium, which polls after a specified amount of time.
  • For example, an element is dynamic and might be loaded after 10 seconds,20 seconds or 30 seconds, or even more.
  • If we declare an explicit wait of 20 seconds, in this case, it will wait for that time before throwing an exception.
  • In this case, the fluent wait is most suitable as it will try to find the element at different frequencies until the final timer runs out.
Wait wait = new FluentWait(driver)

.withTimeout(timeout, SECONDS)

.pollingEvery(timeout, SECONDS)

.ignoring(Exception.class);

Timeout Exception in Selenium Java

Timeout exception generally occurs when a Webdriver wait has finished waiting for a particular element to be present or any condition to be satisfied.

To understand this, Let’s see an example where we will try to search for an element for a few seconds using webdriver wait.

package com.qa.bs;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class timeOutExample {

@Test
public void timeOutTest()
{

System.setProperty("webdriver.chrome.driver","c:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
ChromeDriver driver = new ChromeDriver(options);
driver.get("https://app.hubspot.com/login");

//This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 10 seconds
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username1")));

}
}

For the sake of understanding, the ID for the username given in the above example is incorrect. The driver cannot find the element between 10 seconds, and it throws a timeout exception as demonstrated below.

timeout exception in Selenium Java

This clearly shows that the driver tried to find the element’s visibility for 10 seconds, and as it could not find the element it threw a timeout exception.

BrowserStack Automate Banner 8

Now let’s try to see the same example with the correct id for the username field, and we shall know the test has passed without throwing a timeout exception.

package com.qa.bs;

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

public class timeOutExample {

@Test
public void timeOutTest()
{

System.setProperty("webdriver.chrome.driver","c:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
ChromeDriver driver = new ChromeDriver(options);
driver.get("https://app.hubspot.com/login");

//This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 10 seconds
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));

}
}

 

timeout exception in Selenium Java

Now we can see the same test has passed as the driver was able to find the element within the given time.

Timeout Exception in Selenium Python

Now let’s see the same timeout example in Python. In this example, we have used the presence_of_element_located() function to find the element within the given time.

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome('C:/chromedriver.exe')
driver.get("https://app.hubspot.com/login")

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'username1')))

Here too, we have deliberately given an invalid ID for the username field so that the driver is unable to find the element and throws a timeout exception as below.

Timeout Exception in Selenium Python

If we give the correct ID for the username element, the driver can find the element of the specified time, and the test passes as below.

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome('C:/chromedriver.exe')
driver.get("https://app.hubspot.com/login")

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'username')))

Timeout Exception in Selenium Python

Talk to an Expert

Why use BrowserStack Automate for Selenium Tests?

Here’s why you should use BrowserStack Automate for running Selenium tests:

  • Diverse environment testing: With BrowserStack one can automate Selenium tests across different devices, operating systems and browsers.
  •  Real Devices and Browsers: It is always wiser to test the application on real devices and browsers to simulate a real user experience. Testing on real devices gives the actual confidence about the application performance.
  • Concurrent test execution: Simultaneous test execution of multiple Selenium tests can be achieved which reduces the total execution time, gives quicker feedback and accelerates deployment cycles.
  • Custom Reports with Artifacts: In Automate, custom reports can be generated to provide detailed and customized reports for the automated test execution.
  • Easy Integration with CI/CD Pipeline: BrowserStack’s Automate product can be seamlessly integrated with popular CI/CD tools such as Jenkins, TeamCity, TravisCI
Tags
Automation Testing Selenium Selenium Webdriver