selenium-python
  1. selenium-python-implicit-and-explicit-wait

Selenium Python: Implicit and Explicit Wait

In Selenium automation, waiting for elements to be present or meet certain conditions is crucial for stable and reliable test scripts. Selenium provides two types of waits: implicit and explicit. This guide covers the syntax, examples, output, explanation, use cases, important points, and a summary of implicit and explicit waits in Selenium using Python.

Syntax

Implicit Wait:

driver.implicitly_wait(time_in_seconds)

Explicit Wait:

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

# Example of explicit wait
element = WebDriverWait(driver, timeout).until(
    EC.presence_of_element_located((By.XPATH, "xpath_of_element"))
)

Example

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

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# Navigate to a web page
driver.get("https://example.com")

# Implicit Wait
driver.implicitly_wait(10)  # Waits for 10 seconds for elements to be present

# Explicit Wait
element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "css_selector_of_element"))
)

# Perform actions on the element
element.click()

# Close the browser window
driver.quit()

Output

The output of the example would be the successful execution of the script, performing actions after the waits.

Explanation

  • Implicit Wait: Waits for a specified amount of time for elements to be present before throwing an exception.
  • Explicit Wait: Waits for a specific condition to be true before proceeding further.

Use

  • Implicit Wait: Useful when waiting for elements to appear globally across the entire script.
  • Explicit Wait: Useful when waiting for specific conditions for a particular element.

Important Points

  • Implicit waits affect the entire lifetime of the WebDriver object.
  • Explicit waits are more specific and flexible, allowing conditions based on various expectations.

Summary

In Selenium automation, waiting strategies are essential for handling dynamic elements and ensuring stable test execution. Implicit and explicit waits provide mechanisms for waiting before interacting with elements on a web page. Choose between them based on your specific requirements, and use them judiciously to create robust and reliable Selenium scripts.

Published on: