0

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.

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.