Home > Enterprise >  Quick checking if element exists with Python Selenium
Quick checking if element exists with Python Selenium

Time:09-16

I found this answer about checking the visibility of an element. My problem with this answer is, that it never returns "Element not found". Not only that! It take a very long time to give the error message (below).

from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Firefox()
driver.get('http://www.google.com')


element = driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/a[2]') #this element exists
if element.is_displayed():
    print("Element found")
else:
    print("Element not found")

hidden_element = driver.find_element(By.XPATH,'/html/body/div[1]/div[1]/a[20]') #this one doesn't exist
if hidden_element.is_displayed():
    print("Element found")
else:
    print("Element not found")

I need something that is more efficient and returns False or something another than this error message:

RemoteError@chrome://remote/content/shared/RemoteError.jsm:12:1 WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:192:5 NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.jsm:404:5 element.find/</<@chrome://remote/content/marionette/element.js:291:16

CodePudding user response:

Instead of driver.find_element you can use driver.find_elements method.
Something like this:

if driver.find_elements(By.XPATH,'/html/body/div[1]/div[1]/a[20]'):
    print("Element found")
else:
    print("Element not found")

driver.find_elements will return you a list of web elements matching the passed locator. In case such elements found it will return non-empty list interpreted by Python as a Boolean True while if no matches found it will give you an empty list interpreted by Python as a Boolean False.
To reduce the time it takes here you can define implicitly_wait to some short value, like 1 or 2 seconds, as following:

driver.implicitly_wait(2)

UPD
In case you want to check the element displayed status you can get the element from the list by index, something like following:

elements = driver.find_elements(By.XPATH,'/html/body/div[1]/div[1]/a[20]')
if elements:
    print("Element found")
    if elements[0].is_displayed():
        print("Element is also displayed")
else:
    print("Element not found")

CodePudding user response:

You can check with length of elements

hidden_element = driver.find_elements(By.XPATH,'/html/body/div[1]/div[1]/a[20]') #this one doesn't exist
if len(hidden_element)>0:
    print("Element found")
else:
    print("Element not found"

)

  • Related