Find Element by ID in Selenium: A Complete Guide with Examples

Locating element is a crucial part in Selenium automation testing. There are many element locators available in Selenium, but finding an element by ID is one of the most reliable and most expert-recommended methods.

Why Use ID to Locate Elements?

There are many different element locators available in Selenium. But why should you prefer ID? Here are reasons.
  • Unique Identifier: Generally, ID is unique on the page. That makes it most reliable to use it in the Selenium test scripts.
  • Faster Execution: It is the quickest and fastest way to find an element from the page compared to other locators like XPath or CSS selectors.
  • Improved Stability: There are fewer chances of changing ID in the future. It will reduce your maintenance effort in test scripts.
  • Supported in All Browsers: Works well in all major browsers without any compatibility issues. 
Now let us see why ID is faster than other element locators.

Why is finding an element by ID the fastest element locator strategy?

There are multiple reasons as below.

  • Direct Mapping in the DOM: Finding an element by ID is the fastest element locator strategy because browsers have an optimized lookup mechanism to find elements by ID instantly. 
  • Optimized Browser API: Also, Selenium is using browser's native getElementById() method, which is highly optimized for performance.
  • No Complex Query Processing: No need to search in the entire DOM tree like XPath locator and CSS selectors. findElement(By.id()) retrieves the element in constant time.
  • Minimal Resource Consumption: Since IDs are unique, the search stops as soon as the element is found.
Always prefer to use ID as an element locator if an element has a unique ID.

How to Find ID of element from web page?

You need actual ID of the element to use it in the Selenium test script. There are multiple ways to find the ID of the element. But you can use any of the following ways that I am using to get an element's ID easily.
  1. Using Inspect Element: Right click on Element -> Select Inspect. In the inspect element window, you will get the ID of the element.
  2. Using SelectorsHub Plugin: Install SelectorsHub extension -> Right click on element -> Navigate to SelectorsHub -> and Select Copy ID. It will copy the ID of the element.

Syntax to Find Element by ID in Selenium

Here are examples to find an element by ID in Selenium Python, Java, and C#. Well, there is no language dependency in finding an element by ID. But for better understanding, I have provided an example in all the popular three languages used with Selenium WebDriver.

Python Example to Find Element by ID

from selenium import webdriver
from selenium.webdriver.common.by import By

# Initialize WebDriver
driver = webdriver.Chrome()

# Open a webpage
driver.get("https://example.com")

# Find element by ID
element = driver.find_element(By.ID, "id_of_element")

# Perform action
element.click()

# Close the browser
driver.quit()

Java Example to Find Element by ID

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FindByIdExample {
    public static void main(String[] args) {
        // Set up WebDriver
        WebDriver driver = new ChromeDriver();
        
        // Open webpage
        driver.get("https://example.com");
        
        // Find element by ID
        WebElement element = driver.findElement(By.id("id_of_element"));
        
        // Perform action
        element.click();
        
        // Close browser
        driver.quit();
    }

C# Example to Find Element by ID

from selenium import webdriver
from selenium.webdriver.common.by import By

# Initialize WebDriver
driver = webdriver.Chrome()

# Open a webpage
driver.get("https://example.com")

# Find element by ID
element = driver.find_element(By.ID, "id_of_element")

# Perform action
element.click()

# Close the browser
driver.quit()

Handling NoSuchElementException

For best practices, it is essential to handle NoSuchElementException if Selenium is unable to find an element located by ID. You can include a try catch block as provided in the following examples.

Handling NoSuchElementException in Python

from selenium.common.exceptions import NoSuchElementException

try:
    element = driver.find_element(By.ID, "wrong_id_of_element")
except NoSuchElementException:
    print("Element not found!")

Handling NoSuchElementException in Java

import org.openqa.selenium.NoSuchElementException;

try {
    WebElement element = driver.findElement(By.id("wrong_id_of_element"));
} catch (NoSuchElementException e) {
    System.out.println("Element not found!");
}

Handling NoSuchElementException in C#

using OpenQA.Selenium;
using OpenQA.Selenium.NoSuchElementException;

try
{
    IWebElement element = driver.FindElement(By.Id("wrong_id_of_element"));
}
catch (NoSuchElementException)
{
    Console.WriteLine("Element not found!");
}

Also, you can use an element's ID in XPath like //input[@id='FName'] to find an element by attribute ID in XPath with Selenium.

This way, you can handle NoSuchElementException in Selenium WebDriver if it is unable to find an element by ID.

Alternatives of Find Element By ID

Find element by ID is the best choice if the element has a unique and stable ID. But it is possible that the element you are trying to locate does not have an ID attribute. In this case, you can consider using other attributes like 
If your element contains a link (text inside <a> elements), then you can use
  • Link Text (By.LINK_TEXT)
  • Partial Link Text (By.PARTIAL_LINK_TEXT)

Using Explicit Waits for Better Stability

If the element or page is taking a longer time to load, then it is recommended to use explicit wait to reduce unnecessary errors.

Here is an example of an explicit wait

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Wait until the element is present
element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "element_id"))
)
element.click()
It will explicitly wait for 10 seconds if unable to locate the element by ID while you run the Selenium test.

Common Errors and Troubleshooting Tips

  • ElementNotVisibleException: That means, the element is present on the page but not visible to Selenium. You can try using explicit waits.
  • StaleElementReferenceException: This exception occurs when an element is no longer valid. You can retry to locate it again.
  • InvalidSelectorException: Check if the selector syntax is incorrect.

Best Practices

For best practices, you must consider these points while using find element by ID.
  • Make sure the ID is unique on the page. It will help to avoid wrong element selection.
  • Do not hesitate to use explicit waits if elements take time to load.
  • Use logging to debug test failures effectively.
  • Avoid using dynamically changing IDs in the test script. Such IDs can break the test scripts. 
  • If the element's ID is changing dynamically, and ID is the only choice, then you can use ID in XPath with contains(), starts-with(), or ends-with() functions. It will help you to match partial attribute value. You can refer to this XPath in Selenium tutorial where I mentioned how to handle dynamic changing ID in XPath.
Using find element by ID is one of the best, convenient, and efficient element locator strategies. It is fast, reliable, and easy to use. By following these best practices, you can improve the stability of your test automation.

Still have any questions? You can ask me in the comment.

No comments:

Post a Comment