Home > other >  Check if element is on page with selenium
Check if element is on page with selenium

Time:03-12

I thought doing this

        if driver.find_element_by_xpath("/html/body/div[2]/div[3]/div[1]/div[1]/button"):
            pass

would work, but it doesn't and just returns

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div[3]/div[1]/div[1]/button"}"

CodePudding user response:

There are two main ways to do so:

Using Try / catch

try:
    driver.find_element_by_xpath("/html/body/div[2]/div[3]/div[1]/div[1]/button")
except NoSuchElementException:
    print("Element does not exist")

Using find_elements()

if(len(driver.find_elements_by_xpath("/html/body/div[2]/div[3]/div[1]/div[1]/button")) > 0):
    print("Element exist")
else:
    print("Element does not exist")

For more informations see: https://www.tutorialspoint.com/checking-if-element-exists-with-python-selenium

  • Related