Selenium - wait until element is present, visible and interactable

Benjamin Arvola picture Benjamin Arvola · Dec 1, 2019 · Viewed 38.7k times · Source

I have a Selenium script (Python) that clicks a reply button to make the class anonemail appear. The time it takes for the class anonemail to appear varies. Because of that I have to use sleep until the element has appeared.

I want to wait until the class has appeared instead of using sleep. I have heard about wait commands, but I don't know how to use them.

This is what I have thus far:

browser.find_element_by_css_selector(".reply-button").click()
sleep(5)
email=browser.find_element_by_css_selector(".anonemail").get_attribute("value")

Answer

DebanjanB picture DebanjanB · Dec 1, 2019

As per the best practices:

  • If your usecase is to validate the presence of any element you need to induce WebDriverWait setting the expected_conditions as presence_of_element_located() which is the expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible. So the effective line of code will be:

    WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".reply-button"))).click()
    
  • If your usecase is to extract any attribute of any element you need to induce WebDriverWait setting the expected_conditions as visibility_of_element_located(locator) which is an expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. So in your usecase effectively the line of code will be:

    email = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "element_css"))).get_attribute("value")
    
  • If your usecase is to invoke click() on any element you need to induce WebDriverWait setting the expected_conditions as element_to_be_clickable() which is an expectation for for checking an element is visible and enabled such that you can click it. So in your usecase effectively the line of code will be:

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".reply-button"))).click()
    

References

You can find a couple of detailed discussion in: