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?
- 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.
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.
How to Find ID of element from web page?
- Using Inspect Element: Right click on Element -> Select Inspect. In the inspect element window, you will get the ID of the element.
- 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
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
- Tag Name (By.TAG_NAME)
- Name (By.NAME)
- Class Name (By.CLASS_NAME)
- CSS Selector (By.CSS_SELECTOR)
- XPath (By.XPATH)
- Link Text (By.LINK_TEXT)
- Partial Link Text (By.PARTIAL_LINK_TEXT)
Using Explicit Waits for Better Stability
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()
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
- 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.
Still have any questions? You can ask me in the comment.
No comments:
Post a Comment