Stabilize Automation with Selenium Webdriver Waits in Python


This tutorial is driving you to the concept of Selenium Webdriver waits (Implicit and Explicit Waits) and how to apply them in Python.

If you’re familiar with automation, placing waits in efficient places is very important to stabilize automation. It can deal with issues of unstable network, data slow loading, and generally situations we can’t predict how much time we need. It’s very important, so we have to learn it.

In general, we need to wait in a specific timeout to ensure web elements loaded completely or ready, before interacting with them. Webdriver API provides two types of wait mechanisms to handle such conditions: implicit wait and explicit wait.

Implicit Wait

An implicit wait instructs the WebDriver to re-load the DOM in a defined amount of time to try to locate an element if it does not exist. The implicit wait is set by the function implicitly_wait with an amount of seconds. Executing the below code, you could see an exception raises since it can’t find an element with id ‘id-not-on-site’ in 5 seconds.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(executable_path="C:/files/chromedriver.exe")
driver.implicitly_wait(5)
driver.get("http://google.com")
inputElement = driver.find_element_by_id("id-not-on-site")
inputElement.send_keys("goodevops.com")
inputElement.submit()

driver.close()

Explicit Wait

Almost scenarios of waits are uncertain. Explicit wait works more efficient than implicit wait, but it definitely costs you more efforts. You have to figure out signals to wait in a specific amount of time. Don’t worry! Your efforts are rewarded with more quality or stable scripts.

The following are the two Selenium Python classes for explicit waits.
• WebDriverWait
• Expected Conditions

Example 1: the below code snippet is to wait for an alert dialog appears in 10 seconds

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
from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import TimeoutException

try:
    WebDriverWait(driver,10).until(EC.alert_is_present())
    alert_dialog = driver.switch_to.alert
    print ("Alert message: ", alert_dialog.text)
    alert_dialog.accept()
except (NoAlertPresentException, TimeoutException) as ex:
    print("Alert not present")
finally:
    driver.quit()

Example 2: this code snippet is to wait for an input with innertext ‘close’ appears in 20. If it appears, click on it will be performed.

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[text()='close']"))).click()

Again, applying waits is very important to stabilize automation scripts. Hope these practices can help you in some ways. Success.


Leave a Reply