Home > Blockchain >  Selenium NoSuchElementException When I Want to Detect if an Element Exist
Selenium NoSuchElementException When I Want to Detect if an Element Exist

Time:08-08

I am using selenium in Python to detect if a sign-out button appears after log in. I have tried these, but none of them works:

  1. Using is_displayed()
if not driver.find_element("id","idp_SignOutButton").is_displayed():
        print("fail")
  1. Using isEmpty()
if driver.find_element("id","idp_SignOutButton").isEmpty():
        print("fail")

They return this error message.

I used chrome driver. Any ideas what I am missing here?

CodePudding user response:

If you just want to know if the element exists or not, call find_element() as you are doing, but put it inside a try/except{} block.

from selenium.commons.exceptions import NoSuchElementException

try:
    driver.find_element("id","idp_SignOutButton")
    print("element was found")

except NoSuchElementException:
    print("element was not found")

CodePudding user response:

The simplest and clearest way to check element existence is to use find_elements method. It will not throw exception in case of no element found. No need to use a try/except{} block etc.
find_elements returns a list of found matches. So, in case element exists it will return a non-empty list while in case of no element found it will return an empty list. Since in Python empty list is interpreted as a Boolean False while non-empty list is interpreted as a Boolean True your code can be as following:

if not driver.find_elements("id","idp_SignOutButton"):
        print("fail")
  • Related