How to Check if an Element Exists in Selenium?

Master these element detection to techniques to make your Selenium tests for reliable.

Get Started free
Guide Banner Image
Home Guide How to Check if an Element Exists in Selenium?

How to Check if an Element Exists in Selenium?

Selenium is a powerful tool widely used by developers for automating web testing due to its multi-browser support and scalability. It works by mimicking real-user interactions and detecting elements on a webpage.

In Selenium, an element refers to any interactive object on a webpage, such as buttons, links, or input fields. It is essential to check if an element exists in Selenium before the test script performs any action for the automation sequence to work smoothly.

In this guide, you will learn several element detection techniques that can improve your test stability and help you implement maintainable solutions in your Selenium automation framework.

What is an Element in Selenium?

In Selenium, every object on the webpage that allows interaction with tests is an element. This includes buttons, links, input fields and many more.

These objects are findable through locators in Selenium like ID, name, class, or XPath in the Document Object Model(DOM). Element validation is crucial as even one undetected object can disrupt the entire automation sequence.

Importance of Checking Existence of Element in Selenium

In the present web environment, pages have become increasingly dynamic and complicated. You must perform several tests before deployment for optimal user experience.

Here’s why you should always verify elements in Selenium:

  • Imagine your webpage performs a certain action only after an API response. The test would fail without checking the existence of element in Selenium even if the web application is working fine. This makes element availability check critical for reliable and accurate testing in Selenium.
  • Element detection simplifies debugging and test-script maintenance. You see meaningful error messages/statements instead of random crashes.
  • Page rendering speed is different for every browser. You need to find a middle ground with your test scripts and ensure all elements are ready before interaction. This is only achievable by verifying elements beforehand.
  • Many web applications nowadays use lazy loading to dynamically load content, Element detection ascertains that your tests can handle these changing scenarios effectively.

Methods to Check if an Element Exists in Selenium

Element verification is crucial to ensure your test script runs smoothly and Selenium offers various techniques for this.

Below is a detailed exploration of these methods:

1. findElements Method

The findElements method effectively handles cases where elements might not exist. Unlike findElement, which throws an exception when no element is found, findElements returns an empty list – making it safer for existence checks.

Syntax:

elements = driver.find_elements(By.<locator_type>, "<locator_value>")

if len(elements) > 0:

    # Element exists

else:

    # Element does not exist

Example Code:

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.chrome.service import Service

from selenium.webdriver.chrome.webdriver import Options



# Set up WebDriver

options = Options()

options.add_argument('--headless')  # Run in headless mode

service = Service("C:/chromedriver/chromedriver-win64/chromedriver.exe")  # Replace with the actual path

driver = webdriver.Chrome(service=service, options=options)

try:

    # Navigate to bstackdemo.com

    driver.get("https://bstackdemo.com")




    # Check if the "Add to Cart" button exists

    add_to_cart_buttons = driver.find_elements(By.CLASS_NAME, "shelf-item__buy-btn")

    if len(add_to_cart_buttons) > 0:

        print(f"Element exists! Found {len(add_to_cart_buttons)} 'Add to Cart' button(s).")

    else:

        print("Element does not exist.")

finally:

    driver.quit()

This is a web automation script using Selenium WebDriver to interact with the bstackdemo.com website. It sets up a Chrome WebDriver in headless mode using specified options and a ChromeDriver executable path.

The script navigates to bstackdemo.com and checks for Add to Cart buttons using find_elements to look for elements with the class name shelf-item__buy-btn. If it finds any buttons, it tells us the number; if not, it reports that the element doesn’t exist. This code is straightforward but resilient to timing issues as it doesn’t wait for elements to load.

Output:

Output1findElements

2. Single Line of Code Method

This method is ideal for simple actions but not recommended for complex interactions. It simplifies test scripts, reduces redundancy, and provides an efficient way to verify element presence, enhancing code readability.

Example Code:

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.chrome.service import Service

from selenium.webdriver.chrome.webdriver import Options




# Set up WebDriver

options = Options()

options.add_argument('--headless')  # Run in headless mode

service = Service(r"C:\chromedriver\chromedriver-win64\chromedriver.exe")  # Replace with the actual path

driver = webdriver.Chrome(service=service, options=options)

Try:

  # Navigate to bstackdemo.com

    driver.get("https://bstackdemo.com")



    # Check for "Add to Cart" buttons in a single line

    result = len(driver.find_elements(By.CLASS_NAME, 'shelf-item__buy-btn'))

    print(f"'Add to Cart' buttons found: {result}" if result > 0 else "No 'Add to Cart' buttons found.")

finally:

    driver.quit()

The single line of code in the example simplifies element presence checks and result output. It first uses driver.find_elements(By.CLASS_NAME, ‘shelf-item__buy-btn’) to locate all elements with the class name shelf-item__buy-btn.

The len() function then counts how many such elements are found. The result is stored in the variable result. The ternary conditional operator (if result > 0 else) prints either the count of found elements (“Add to Cart buttons found: X”) if any exist, or a message saying no buttons were found (“No ‘Add to Cart’ buttons found.”).

Output:

Output2Single line of Code

3. Count() Method:

The count() method is effective for determining how many times particular elements are found in Selenium

count = len(driver.find_elements(By.CLASS_NAME, 'example-class'))

For instance, this line makes use of the find_elements method to locate all elements that have the specified class name. It then applies Python’s len() function to find the total number of those elements. This gives a precise count of the elements that are present on the page.

4. is_displayed() and is_enabled() with expected_conditions Method

The is_displayed() and is_enabled() methods in Selenium with expected_conditions confirm element visibility and interactivity status.

First, make sure you can see the button and interact with it

wait.until(EC.visibility_of_element_located((By.ID, 'button-id')))  # Wait for button to show up

wait.until(EC.element_to_be_clickable((By.ID, 'button-id')))  # Wait until you can click it



# Now you can check if it's visible and enabled before doing anything

button = driver.find_element(By.ID, 'button-id')

if button.is_displayed() and button.is_enabled():

    button.click()

It is used when testing the functionality of UI objects like buttons or forms. The expected_conditions wrapper adds explicit wait to handle dynamic loading and makes tests more stable.

5. Using Selenium’s built-in exception

Selenium is known for handling automated testing scenarios and web element interactions with built-in exceptions.

    # Try to find and click the button

    driver.find_element(By.ID, 'submit-button').click()

except NoSuchElementException:

    # Log issue and maybe take a screenshot

    print("Couldn't find the submit button - page might be broken")

    driver.save_screenshot('error.png')

except TimeoutException:

    # Maybe retry or refresh the page

    print("Page took too long to respond") 

    driver.refresh()

This enhances reliability to your tests by effectively handling common issues like missing elements or slow loading pages. You can customize the error handling to suit the specific needs of your test cases.

BrowserStack Automate Banner

How to check if Element exists in Selenium on Browserstack?

To check if an element exists in Selenium tests on BrowserStack, you need to configure the WebDriver with the correct BrowserStack capabilities and utilize standard Selenium methods.

Here’s how to do it:

  • First, set up the BrowserStack integration by entering your username, access key, and the desired metrics for the browser and operating system.
  • Next, use Selenium commands such as find_elements or WebDriverWait to identify elements during your test execution.
  • Your test scripts are executed on BrowserStack’s cloud infrastructure, so you can verify the presence of elements across various browsers and devices. BrowserStack executes scripts seamlessly and offers detailed test logs, screenshots, and video recordings for to help effectively troubleshoot any issues related to element presence.

Common Errors while Checking Elements in Selenium (With Solutions):

Here are some common errors that users face while checking element in Selenium:

1. NoSuchElementException

This error typically occurs when the dynamic content on the page hasn’t fully loaded before Selenium attempts to find the element. This can be resolved by adding appropriate waits.

# Error: Element not found

driver.find_element(By.ID, 'missing-id')



# Solution: Add explicit wait

try:

element = WebDriverWait(driver, 10).until(

        EC.presence_of_element_located((By.ID, 'missing-id'))

    )

except TimeoutException:

    print("Element not found after waiting")

2. ElementNotVisibleException

Occurs when an element is not located and displayed properly. It is easily fixed with explicit waits.

# Error: Hidden element interaction

hidden_element.click()



# Solution: Wait for visibility

visible_element = wait.until(

    EC.visibility_of_element_located((By.ID, 'element-id'))

)

visible_element.click()

3. StaleElementReferenceException

This error arises when a previously located element becomes detached from the DOM due to page updates, such as a page refresh. The solution is to relocate the element after the page changes.

# Error: Element reference lost after page update

element = driver.find_element(By.ID, 'dynamic-id')

# Page updates

element.click()  # Fails



# Solution: Re-locate element after page change

wait.until(EC.staleness_of(element))

new_element = driver.find_element(By.ID, 'dynamic-id')

4. ElementClickInterceptedException

Occurs when 2 elements overlap and block each other’s visibility. Can be fixed with explicit waits or by using JavaScript.

# Error: Element covered by another element

button.click()



# Solution: Use JavaScript executor

driver.execute_script("arguments[0].click();", button)

Talk to an Expert

Useful Resources for Automation Testing in Selenium

Methods, Classes, and Commands

Configuration

XPath

Locators and Selectors

Waits in Selenium

Frameworks in Selenium

Miscellaneous

Best Practices, Tips and Tricks

Design Patterns in Selenium: Page Object Model and Page Factory

Action Class

TestNG and Selenium

JUnit and Selenium

Use Cases

Types of Testing with Selenium

Conclusion

When working with Selenium, checking for elements might seem like a small detail, but it’s actually the foundation of reliable test automation. The techniques covered here give test engineers the required tools to build dependable automation frameworks.

These element detection techniques become even more powerful when combined with BrowserStack Automate’s cloud infrastructure. Instead of wrestling with local setup and browser compatibility issues, teams can focus on writing robust tests using these detection methods while BrowserStack handles the heavy lifting of cross-browser testing. The platform’s detailed logging, screenshots, and video recordings make it straightforward to debug element detection issues across different browsers and devices.

Tags
Automation Frameworks Automation Testing Selenium