Last modified: Oct 23, 2024 By Alexander Williams

Python Selenium: Explicit Waits

Explicit waits in Python Selenium allow you to wait for specific conditions before performing an action. This ensures that elements are ready before interacting with them.

What are Explicit Waits?

Unlike implicit waits, explicit waits allow you to pause your script until a certain condition is met. This is useful when elements take time to load or appear on the page.

Why Use Explicit Waits?

Explicit waits provide more control over how long the script should wait for an element to be visible, clickable, or present on the page. This reduces the risk of errors in your tests.

How to Use Explicit Waits in Python Selenium

To use explicit waits, you need to import the WebDriverWait class and expected_conditions from the Selenium library.


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

# Initialize the driver
driver = webdriver.Chrome()

# Open a webpage
driver.get('https://example.com')

# Define explicit wait
wait = WebDriverWait(driver, 10)

# Wait until an element is clickable
element = wait.until(EC.element_to_be_clickable((By.ID, 'example-id')))

# Perform an action on the element
element.click()

# Close the driver
driver.quit()

In this example, the script will wait for up to 10 seconds until the element with the ID 'example-id' becomes clickable. If it doesn't, an exception is raised.

Common Explicit Wait Conditions

There are several common conditions you can use with explicit waits, such as:

  • presence_of_element_located() – Waits for an element to be present in the DOM.
  • visibility_of_element_located() – Waits for an element to be visible.
  • element_to_be_clickable() – Waits for an element to be clickable.

Learn more about Selenium's expected conditions for a full list of options.

Explicit Wait vs Implicit Wait

Explicit waits offer greater control, as they are tied to specific elements or conditions. In contrast, implicit waits apply globally to all elements.

Handling Timeout Exceptions

If the condition isn't met within the specified time, a TimeoutException is raised. You can catch and handle this exception to avoid abrupt script failures.


from selenium.common.exceptions import TimeoutException

try:
    element = wait.until(EC.element_to_be_clickable((By.ID, 'example-id')))
except TimeoutException:
    print("Element not clickable within the time limit")

Conclusion

Explicit waits in Python Selenium provide precise control over waiting for elements or conditions. This improves test reliability, especially for dynamic content or delayed elements.

For more details, check out related articles like Getting Element Attributes or Taking Screenshots in Selenium.