Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Quick checking if element exists with Python Selenium

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading