Selenium Webdriver introduces the concept of waits for the AJAX-based application. There are two types of waits:
- Implicit Wait
- Explicit Wait
In Selenium, “waits” are used to hold the execution of the test script until a certain condition is met. This is important because web pages may not load at the same speed, and elements on a page may take some time to become available or change state.
There are two main types of waits in Selenium:
- Implicit Wait:
- An implicit wait is a type of wait that sets a global wait timeout for the WebDriver instance. Once set, this timeout will be applied to all subsequent commands throughout the entire duration of the WebDriver instance.
- It waits for a certain amount of time before throwing a “No Such Element Exception.” If the element is found before the timeout expires, the script will proceed with the next steps immediately.
from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10) # 10 seconds implicit wait - Explicit Wait:
- An explicit wait is more specific and provides better control over wait conditions. It allows the WebDriver to wait for a certain condition to occur before proceeding further in the code.
- WebDriverWait in combination with ExpectedConditions is commonly used for explicit waits.
element = WebDriverWait(driver, 10).until(from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
EC.presence_of_element_located((By.ID, “some_element_id”))
)In this example, the script will wait up to 10 seconds for the presence of the element with the specified ID before throwing a TimeoutException.
Using a combination of implicit and explicit waits is a good practice in Selenium testing to handle dynamic web pages and ensure stable test execution.