Selenium continue script even if element is not present

Viewed 191

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.

2 Answers

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

You should be able to use a try statements, it would look like this:

try:
    driver.find_element(By.ID, "FirstName").send_keys("MyFirstName")
except:
    print("Element not found")

try:
    driver.find_element(By.ID, "LastName").send_keys("MyLastName")
except:
    print("Element not found")

try:
    driver.find_element(By.ID, "PhoneNumber").send_keys("myPhoneNumber")
except:
    print("Element not found")

try:
    driver.find_element(By.ID, "Email").send_keys("myEmail")
except:
    print("Element not found")

It should print out "Element not found" and then continue the script

Related