Python - Selenium - Wait for element to appear

By xngo on June 20, 2019

Nowadays, most websites are very interactive and use AJAX alot. Therefore, some elements within a page may load at different time intervals. This makes locating elements difficult. If an element is not found, Selenium will throw an exception. Luckily, Selenium provides out of the box wait functions for your convenience.

The code below shows how to wait for input field to appear before entering some text.

import time
 
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 chrome driver.
driver = webdriver.Chrome()
 
# Open the webpage.
driver.get("https://openwritings.net/sites/default/files/selenium-test-pages/selenium-test-wait.html")
 
# Find and click on button.
button = driver.find_element_by_tag_name("button")
button.click()
 
# Wait for input element to load.
##################################
# Wait for a maximum of 10 seconds for the input field to appear.
input = WebDriverWait(driver, 10).until(
                    EC.presence_of_element_located((By.TAG_NAME, "input"))
                )
 
# Type in text in input field.
input.send_keys('Waited and found this input field')
##################################
 
 
# Pause for 10 seconds so that you can see the results.
time.sleep(10)
 
# Close.
driver.close()

Here is a video showing the code above in action.

Video showing Selenium waiting for element to appear

Expected Conditions

Selenium also provides some commonly used expected conditions so that you don't have to reinvent the wheel. They are:

  • title_is
  • title_contains
  • presence_of_element_located
  • visibility_of_element_located
  • visibility_of
  • presence_of_all_elements_located
  • text_to_be_present_in_element
  • text_to_be_present_in_element_value
  • frame_to_be_available_and_switch_to_it
  • invisibility_of_element_located
  • element_to_be_clickable
  • staleness_of
  • element_to_be_selected
  • element_located_to_be_selected
  • element_selection_state_to_be
  • element_located_selection_state_to_be
  • alert_is_present

Reference

  • For more information, see the API.
  • https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.