How to Use Selenium WebDriver Waits using Python
This tutorial will guide you through the concept of Selenium Webdriver waits (Implicit and Explicit Waits) and how to use them in Python.
If you are doing automation in Selenium Python and wish to write error-free scripts, then you must learn to use waits. They let you handle any unexpected condition which may occur.
While automating a web application, you intend to write a script which can execute the following tasks.
Click here to Go Back to main Selenium Python tutorial.
- Load up the browser,
- Open up the website,
However, the test script could sometimes fail due to the following reasons.
In these cases, we need to wait for the time to allow the web elements to load completely, before using them in our tests. Webdriver API provides two types of wait mechanisms to handle such conditions. We will discuss these wait conditions one by one in detail.
Selenium Webdriver Waits in Python
The two types of Selenium Webdriver waits are :
An implicit wait directs the WebDriver to poll the DOM for a certain amount of time (as mentioned in the command) when trying to locate an element that is not visible immediately. The default value of time that can be set using Implicit wait is zero. Its unit is in seconds. Implicit wait remains associated with the web element until it gets destroyed.
Follow the below coding snippet illustrating the use of Implicit wait in Python.
from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.implicitly_wait(100) driver.get("http://google.com") driver.maximize_window() print("Implicit Wait Example") inputElement = driver.find_element_by_id("lst-ib") inputElement.send_keys("Techbeamers") inputElement.submit() driver.close()
In the above code, the implicitly_wait( ) method tells the Webdriver to poll the DOM again and again for a certain amount of time. The timeout in this example is 100 seconds which will trigger if the target element is not available during that period.
Explicit Wait
There may be scenarios when the wait time is uncertain. Explicit waits work as a savior there. Here we can define certain conditions, and Selenium WebDriver will proceed with the execution of the next step only after this condition gets fulfilled.
The explicit wait is the most preferred way of implementing Selenium webdriver waits in a test script. It provides the flexibility to wait for a custom condition to happen and then move to the next step.
- WebDriverWait, and
- Expected Conditions class of the Python.
To understand its usage, let’s take an example of a Simple JavaScript alert on a webpage. A button is present on the web page to trigger that alert.
Simple Alert Demonstration
Press button underneath to generate an alert.
function alertFunction()