Skip to content
Advertisement

Selenium continue script even if element is not present

This is an example of what my code currently looks like,

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")

When for instance element ID “PhoneNumber” isn’t present, the script will stop with the error code “Unable to locate element”, what needs to be added or changed in order to continue the script without abruption even if a certain element is not present?

Thanks in advance.

Advertisement

Answer

You can implement try/except block

from selenium.common.exceptions import NoSuchElementException

...
driver.find_element(By.ID, "LastName").send_keys("MyLastName")
try:
    driver.find_element(By.ID, "PhoneNumber").send_keys("myPhoneNumber")
except NoSuchElementException:
    print("No Phone number input field found")
driver.find_element(By.ID, "Email").send_keys("myEmail")
...

or use conditional operator as below:

if driver.find_elements(By.ID, "PhoneNumber"):
    driver.find_element(By.ID, "PhoneNumber").send_keys("myPhoneNumber")
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement