0

Trying to resolve an issue where I need to check if an element is on a page if it exists then perform a piece of code if not then continue with script. The issue I have is that if the element does not appear then script fails with 'Failed to find element'

What I currently have is:

form_error = s.driver.find_element_by_xpath("//div[contains(@class,'screen-new-error')]")
form_error = form_error.get_attribute('textContent')
form_error = form_error[6:].strip()
             
if form_error == "There was a problem with the Form":
   result = "FAIL"
else:
  result = "PASS"
Seán Dempsey
  • 105
  • 3
  • 10

1 Answers1

1

you have a few options:

1.

from selenium.common.exceptions import NoSuchElementException        
def check_exists_by_xpath(xpath):
    try:
        webdriver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True
  1. call find_element inside a try/catch
Tal Folkman
  • 2,368
  • 1
  • 7
  • 21