Search code examples
pythonselenium-webdriverwebdriverwait

Python Selenium click in webdriverwait versus find_element


I'm having trouble understanding what are the differences between these two blocks of codes. Sending clicks both work in webdriverwait and find_elements.

Code 1

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.Chrome(options=options)
wait = WebDriverWait(driver, 45)


wait.until(EC.presence_of_element_located((By.LINK_TEXT, "ABC"))).click()

Code 2

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.Chrome(options=options)
wait = WebDriverWait(driver, 45)

wait.until(EC.presence_of_element_located((By.LINK_TEXT, "ABC")))
driver.find_element(By.LINK_TEXT,"ABC").click()
    

Solution

  • wait.until(EC.presence_of_element_located((By.LINK_TEXT, "ABC")))
    

    This will return a webElement and you can call methods which are available for webElement i.e click(), send_keys(), clear() etc.

    driver.find_element(By.LINK_TEXT,"ABC")
    

    This also does the same thing i.e: it will return a webElement.

    Difference: The main difference between these two: WebDriverWait is an explicit wait in Selenium that means if element is not found in DOM then it will try again after 500ms which is .5 sec again until 45 sec (since you've defined 45 sec in the constructor call). if found within this time it will return the webElement, otherwise it will raise timeOutException.

    On the other hand driver.find_element will try to find the element immediately if found it will return the webElement if not, exception will be raised either NoSuchElement or some other.

    You can read more about explicit wait here