Sobes.tech
Middle

What are the differences between explicit and implicit waits in the context of test automation?

sobes.tech AI

Answer from AI

Explicit Wait — is code that pauses execution until a certain condition is met or the maximum wait time has elapsed. It is targeted at a specific element or event.

  • WebDriverWait in Selenium is an example of explicit wait.

Implicit Wait — is a setting applied to the driver throughout its lifetime. It instructs the driver to wait a certain amount of time before throwing a NoSuchElementException when searching for an element. If the element appears earlier, the wait stops.

  • It is set once for the entire driver session.

Main differences:

Attribute Explicit Wait Implicit Wait
Application To a specific condition / element To the entire driver session
Flexibility High, can wait for specific conditions Low, waits only until the element appears
Configuration For each wait case separately Once for the entire driver
Selenium example WebDriverWait(driver, time).until(...) driver.implicitly_wait(time)

Example of explicit wait in Python (Selenium):

# Waiting until the element becomes visible
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

try:
    element = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.ID, "my_element_id"))
    )
finally:
    # Actions after waiting or handling TimeoutException
    pass

Example of implicit wait in Python (Selenium):

# Setting implicit wait
driver.implicitly_wait(10) # Wait up to 10 seconds before throwing NoSuchElementException

# Then all find_element/find_elements will use this wait
element = driver.find_element(By.ID, "some_id")

Using explicit and implicit waits together can lead to unpredictable behavior. It is recommended to use explicit waits for most specific cases, and either not to use implicit wait or to use it cautiously and with understanding of its global effect. Explicit waits are preferable as they provide more granular control over the waiting process.