What are Selenium Timeouts?

Timeouts in Selenium are the longest periods a WebDriver will wait for specific circumstances or events to happen during a web page interaction. In Selenium, there are many kinds of timeouts:

1. Implicit Wait

Implicit wait is used in software testing or web automation. It is a mechanism used to manage the interaction time among the web elements.

  • It controls and instructs the WebDriver to wait for a certain amount of time, before they throw any exception, on not finding the requested element on time.
  • While working with Selenium in web automation too, it instructs a WebDriver to wait and poll the DOM until the webelement is found or implicit wait time is elapsed, whichever happens first.
  • It tells the WebDriver to wait for a specified amount of time before attempting to locate an element or to throw any exception.
  • The WebDriver will go on to the next stage if the element is located before the implicit wait time runs out.
  • A TimeoutException is triggered if the element cannot be located in the allotted amount of time.

Example:

Python3




#program for implicit_wait
 
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
 
# Create a WebDriver instance with implicit wait set to 10 seconds
driver = webdriver.Chrome()
# Set the implicit wait to 10 seconds
driver.implicitly_wait(10
driver.maximize_window()
 
# Navigate to a webpage
driver.get("https://www.amazon.in/")
 
# Find an element using find_element method
 
ele = driver.find_element(By.ID, "twotabsearchtextbox")
time.sleep(4)
 
# Perform some action on the element
 
ele.send_keys("iphone")
time.sleep(4)
 
# Close the browser
driver.quit()


Output:

Output for implicit wait in Selenium

Explanation:

In the code given above, the driver will wait up to 10 seconds by regularly polling the DOM to find the element. If the element is found within the 10 seconds, it will be written back, or, if the element is not found past 10 seconds, TimeoutException will occur.

2. Explicit Wait

Explicit wait refers to a context used for handling time related synchronization issues, which mostly occurs in a system having different program execution speeds.

  • Due to this, it leads to pause or a deliberate delay in the execution of a particular program, until its certain conditions get satisfied and fulfilled before proceeding further.
  • By explicitly waiting for a condition to be met, developers can avoid race conditions and ensure that the program progresses only when it is in a valid state.
  • In web automation with Selenium too, it is a condition which is defined on the WebDriver to wait for a certain condition to occur within the elapsed time before proceeding to the next stage in the script or code.
  • This means, that two conditions are checked in one wait condition, an elapsed time and at the same time, the desired condition to occur.

Example:

Python3




#program for explicit_wait
 
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
 
# Create a WebDriver instance
driver = webdriver.Chrome()
driver.maximize_window()
 
# Navigate to a webpage
driver.get("https://www.amazon.in/")
 
# Define an explicit wait with a timeout of 10 seconds
wait = WebDriverWait(driver, 10)
 
# Wait for an element with a specific condition (in this case, the element's presence)
element = wait.until(EC.presence_of_element_located((By.ID, "twotabsearchtextbox")))
time.sleep(3)
 
# Once the element is located, perform some action on it
element.send_keys("bestsellers books fiction")
time.sleep(3)
 
# Close the browser
driver.quit()


Output:

Output for explicit wait in Selenium

Explanation:

  • In the code given above, if you want to access any link before moving forward within the stipulated time (here, 10 seconds), you will be waiting for 10 seconds while the element (or link) is available on the webpage.
  • At the same time, checking for the ExpectedCondition for the presence of the element (or link) located.
  • These ExpectedConditions can be anything, they can be ‘elementToBeClickable’, ‘TitleContains’, ‘ElementIsVisible’, ‘presence_of_element_located’, etc.
  • To provide the element and condition to wait for, you may use the WebDriverWait class in conjunction with the expected_conditions module.
  • The WebDriver keeps running the script if the condition is satisfied within the allotted timeout, otherwise, TimeoutException gets triggered.
  • Even though it depends upon the situation, explicit wait makes more sense because it gives you the control.
  • So, you can choose both wait time as well as ExpectedCondition, especially in AJAX based applications where the elements are already present on the webpage but, not accessible or not clickable or not enabled.

3. Page Load Timeout

Page load timeout suggests a webpage or an application to wait for a maximum amount of time to load itself and its pages successfully, before coming to a conclusion whether the webpage or the application is working or not. When a user or a system initiates a request for a webpage or an application then, there is an expectation that the specified action will complete itself within a limited timeframe. If this exceeds then, the system gets compelled to take some predefined actions, such as signaling an error or throwing a timeout message as an exception. While working with Selenium in web automation too, the Selenium WebDriver would take a maximum time to wait for a webpage to load itself completely. One should be very cautious while setting an appropriate timeout for a page, as this can vary among pages in terms of complexity and loading times due to factors such as slow internet connection, heavy JavaScript, or any asynchronous requests (e.g., AJAX). It is set using the set_page_load_timeout method on the WebDriver instance. If the page doesn’t load within the specified time, a TimeoutException is raised. This is specifically used for handling page load events.

Example:

Python3




#python program for page load timeout
 
from selenium import webdriver
# Create a WebDriver instance with a page load timeout of 30 seconds
driver = webdriver.Chrome()
driver.set_page_load_timeout(2)
try:
    # Attempt to navigate to a webpage
    driver.get("https://www.flipkart.com/")
    # If the page loads successfully, you can continue with your interactions
    # For demonstration purposes, let's print the page title
    print("Page title:", driver.title)
except Exception as e:
    # If the page load timeout is exceeded, an exception (TimeoutException) is raised
    print("Page load failed:", str(e))
finally:
    # Close the browser
    driver.quit()


As shown above, when the page exceeds its page load time (here, 2 seconds), a TimeoutException is raised.

Output:

Output for page load timeout

4. Script Timeout

Script timeout, generally, refers to the maximum amount of time during which a script or a program is allowed to execute itself, before being considered as time consuming. This mechanism also helps in handling the scripts or programs, preventing them to run indefinitely, which further could result in performance issues or unresponsiveness in a system. In the context of web automation with Selenium too, it is the maximum time limit during which a script (especially, a JavaScript code) is allowed to execute or run itself within a web browser. With the help of this, the WebDriver easily allows for the execution of JavaScript in a page. It is set using the set_script_timeout method on the WebDriver instance. If a piece of JavaScript code running in the page takes longer than the specified time to execute, a TimeoutException is raised.

Example:

Python3




#python program for script_timeout
 
from selenium import webdriver
# Create a WebDriver instance with a script timeout of 20 seconds
driver = webdriver.Chrome()
driver.set_script_timeout(10)
try:
    # Execute a JavaScript operation that takes a long time to complete
    driver.execute_script("for(let i=0; i<1000000; i++);")
    # If the script execution completes within the specified timeout, you can continue
    print("Script executed successfully")
except Exception as e:
    # If the script timeout is exceeded, an exception (TimeoutException) is raised
    print("Script execution failed:", str(e))
finally:
    # Close the browser
    driver.quit()


As shown above, since, the script executes itself within the maximum time limit, successful execution of the script is shown as its output.

Output:

Output for script timeout

How to set page load timeout in Selenium?

Page load timeouts play a significant role in web development and user experience, acting as a safeguard against slow-loading pages and contributing to the overall success of a website or web application. Developers work diligently to manage and optimize load times to keep users engaged and satisfied. This article focuses on discussing how to set page load timeouts in Selenium.

Similar Reads

What are Selenium Timeouts?

Timeouts in Selenium are the longest periods a WebDriver will wait for specific circumstances or events to happen during a web page interaction. In Selenium, there are many kinds of timeouts:...

Why page load timeout matters?

...

What is Timeout Exception?

...

How page load timeout works in Selenium?

...

How to handle timeout exception in Selenium?

...

How to set page load timeout in selenium?

As talked about page load timeout, it is an important asset which every webpage on a browser requires and needs to have. There are various reasons for this, which are briefly discussed below:...

Conclusion

Now, coming to the timeout exception, it is a type of exception that arises when a program or script runs out of its allotted time to complete a particular task or action. Also, many programming languages and frameworks use this to handle those operations that comparatively take longer time to execute themselves, so that they do not hang for long....