Search code examples
pythonseleniumfindelement

Unable to find element using Selenium


Using Selenium, I am unable to locate the "email" element on the Udemy website.

Here's what I tried:

browser.get('https://www.udemy.com/join/login-popup/')
browser.implicitly_wait(5)

email = browser.find_element(By.ID, 'email--1')
print(email)

but it gives NoSuchElementException while "email" element isn't even in an iframe, as far as I know.

So, how can I locate this specific element?


Solution

  • In this case, you're probably looking for the element before the page loads.

    You should use the WebDriverWait class of Selenium and the condition presence_of_element_located of the expected_conditions, as shown in the example below:

    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.wait import WebDriverWait
    
    
    browser.get('https://www.udemy.com/join/login-popup/')
    timeout = 20  # Number of seconds before timing out.
    email = WebDriverWait(browser, timeout).until(EC.presence_of_element_located((By.ID, 'email--1')))
    email.send_keys("[email protected]")
    

    In the above snippet, Selenium WebDriver waits up to 20 seconds before throwing a TimeoutException, unless it finds the element to return within the above time. WebDriverWait, by default, calls the ExpectedCondition every 500 milliseconds until it returns successfully.

    Finally, presence_of_element_located is an expectation for determining whether an element is present on a page's DOM, without necessarily implying that the element is visible. When the element is found, the locator returns the WebElement.