Reputation: 559
I am using Selenium webdriver with Python to print the contents an element but if it does not exist on the page it breaks my code and returns an exception error.
print (driver.find_element_by_id("TotalCost").text)
NoSuchElementException: Message: no such element: Unable to locate element
{"method":"id","selector":"TotalCost"}
What can i do to fix this error?
Upvotes: 1
Views: 1171
Reputation: 15962
Catch the exception in a try...except
block:
from selenium.common.exceptions import NoSuchElementException
try:
print(driver.find_element_by_id("TotalCost").text)
except NoSuchElementException:
print("Element not found") # or whatever you want to print, or nothing
Could also do it this way for clarity:
try:
elem = driver.find_element_by_id("TotalCost")
except NoSuchElementException:
pass
else:
print(elem.text)
Upvotes: 2