user901
user901

Reputation: 75

Selenium wait until element by ID is present or visible

How do I have Selenium wait until a certain element by ID is present on the page?

driver.find_element(By.ID, "FirstName").send_keys("MyFirstName")
driver.find_element(By.ID, "LastName").send_keys("MyLastName")
driver.find_element(By.ID, "PhoneNumber").send_keys("myPhoneNumber")
driver.find_element(By.ID, "Email").send_keys("myEmail")

For instance line 3, might not be present on the page I want it to wait until the element is present, then do the certain task and proceed with the next line of the code.

Upvotes: 1

Views: 12925

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193088

To wait until the element is present to send a character sequence you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using ID:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "PhoneNumber"))).send_keys("user901")
    
  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#myPhoneNumber"))).send_keys("user901")
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='myPhoneNumber']"))).send_keys("user901")
    
  • Note: You have to add the following imports :

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

Upvotes: 3

Gaj Julije
Gaj Julije

Reputation: 2183

You can use this.

Java:

WebDriverWait w1 = new WebDriverWait(driver, 5);
w1.until(ExpectedConditions.visibilityOfElementLocated(By.id("submit_btn")));

Python:

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

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()

See more on: https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html

Upvotes: 5

Related Questions