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.
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?
CodePudding user response:
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