Reputation: 191
I'm trying to write and if/else statement if my find_element_by_xpath returns a valid element or not an
price = driver.find_element_by_xpath("//div[@class='price']").text
location = driver.find_element_by_xpath("//div[@class='listing__address']").text
if (SOMETHINGGOESHEREIFELEMENTEXISTS)
print(price, location)
driver.quit()
else:
print("QUITING!")
driver.quit()
In both cases I want to do a driver.quit.
thanks.
Upvotes: 0
Views: 359
Reputation: 2076
As per the docs, find_element_by_xpath()
raises a NoSuchElementException
exception when it fails. Then the following should work:
try:
price = driver.find_element_by_xpath("//div[@class='price']").text
location = driver.find_element_by_xpath("//div[@class='listing__address']").text
print(price, location)
except NoSuchElementException:
print("QUITTING!")
driver.quit()
Upvotes: 2