1

I am trying to automate a page wherein the page can sometimes lead to a custom error page like the below snapshot. The scenario is the page doesn't encounter an error often but when it happens I want to display a message.

enter image description here

The code that I tried is as follows:

login_actions.enter_username(self.username)
login_actions.enter_password(self.password)
login_actions.login()
error_mesg = driver.find_elements(by=By.XPATH, value="//h2[@class='exception-http']")
if error_mesg:
    print("encountered an error")
else:
    #continue with the actions

With the above code, the web driver tries to find the element first which doesn't appear often and the test case fails. Can anyone suggest a solution to find the presence of elements?

Libin Thomas
  • 829
  • 9
  • 18
  • Does this answer your question? [Selenium: Check for the presence of element](https://stackoverflow.com/questions/50610553/selenium-check-for-the-presence-of-element) – SiKing Aug 09 '22 at 14:49
  • It didn't work for me :( But thanks for the suggestion – Libin Thomas Aug 11 '22 at 13:45

1 Answers1

0

To handle the probable custom error page you can wrapup the validation within a try-except{} block and catching the NoSuchElementException you can use the following solution:

login_actions.enter_username(self.username)
login_actions.enter_password(self.password)
login_actions.login()
try:
    driver.find_element(by=By.XPATH, value="//h2[@class='exception-http']")
    print("encountered an error")
    # steps to leave the error page to continue with the other actions
except NoSuchElementException:
    pass
# steps to continue with the other actions
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352