fightstarr20
fightstarr20

Reputation: 12598

Python Selenium crashes when element not found

I am using Python Selenium to open a URL from a list and find a certain element. like so...

driver.get('http://www.example.com.com/')
inputElement = driver.find_element_by_id("my-field")

If the element exists then everything works fine, but if the element can't be found then the script crashes with en error...

Unable to locate element:

Is this correct behaviour and is there a way to deal with this instead of crashing out?

Upvotes: 1

Views: 3166

Answers (3)

Oleksandr Makarenko
Oleksandr Makarenko

Reputation: 808

Sometimes the element does not appear at once, for this case we need to use explicit wait. You can just check if the element exist, without crashes.

browser = webdriver.Chrome()
wait = WebDriverWait(browser, 5)

def is_element_exist(text):
    try:
        wait.until(EC.presence_of_element_located((By.ID, text)))
    except TimeoutException:
        return False

Solution without try/ except:

def is_element_exist(text):
    elements = wait.until(EC.presence_of_all_elements_located((By.ID, text)))
    return None if elements else False

How explicit wait works you can read here.

Imports:

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

Upvotes: 1

Bryan Oakley
Bryan Oakley

Reputation: 385970

It is correct behavior.

You can catch the exception, like you can any exception:

from selenium.common.exceptions import NoSuchElementException
...
try:
    driver.get('http://www.example.com.com/')
    inputElement = driver.find_element_by_id("my-field")
except NoSuchElementException:
    print("couldn't find the element")

Upvotes: 9

Andrii Rusanov
Andrii Rusanov

Reputation: 4606

Yes, it is. From the docs:

... With this strategy, the first element with the id attribute value matching the location will be returned. If no element has a matching id attribute, a NoSuchElementException will be raised.

And the exception could be catched of course(like mentioned in another answer).

You can find docs here: http://selenium-python.readthedocs.org/locating-elements.html#locating-by-id

Upvotes: 1

Related Questions