Understanding Locators in Selenium (ID, Name, XPath, CSS)
Understanding Locators in Selenium (ID, Name, XPath, CSS)
Introduction
In Selenium, locators are how you find elements on a web page to interact with them.
Without locators, Selenium can’t click buttons, type in fields, or check text!
Choosing the right locator makes your automation fast, reliable, and easy to maintain.
Let’s explore the four most popular locators in Selenium:
ID
Name
XPath
CSS Selector
1. ID Locator
The simplest and fastest locator
Targets the element’s unique
id
attributeIDs are supposed to be unique per page
Example:
When to use?
Use ID if available and unique
Preferred for speed and reliability
2. Name Locator
Finds elements by their
name
attributeSometimes multiple elements share the same name, so be careful
Example:
When to use?
Use when ID is not available
Often used for form input fields
3. XPath Locator
XPath is a powerful language to find elements by path in the HTML tree
Can locate elements by tag, attribute, text, or relationship
Example:
Types of XPath:
Absolute XPath: starts from root (not recommended)
Example:/html/body/div[2]/form/input[1]
Relative XPath: starts from anywhere, better for maintenance
Example://input[@type='text']
When to use?
Use XPath for complex or dynamic elements
Good for elements without ID or Name
Can navigate parent/child relationships
4. CSS Selector Locator
Uses CSS rules to find elements
Faster than XPath in most browsers
Can select by tag, class, ID, attribute, and more
Example:
Common CSS selectors:
By ID:
#username
By class:
.btn-primary
By attribute:
input[name='password']
Combining selectors:
div.content > input[type='text']
When to use?
Use CSS Selector for simple to moderately complex locators
Faster and cleaner than XPath for many cases
Tips for Using Locators
Always try ID first — it’s the fastest and most reliable.
Use Name if ID is not available.
Use CSS Selector for clean and fast selection when ID/Name aren’t present.
Use XPath for complex cases or when you need to navigate the DOM tree.
Avoid Absolute XPath as it breaks easily.
Test your locators with browser developer tools (
Inspect Element
→ Console).
Example: Using Different Locators in Python
Conclusion
Locators are the key to effective Selenium automation.
Choosing the right locator improves test speed, reliability, and maintainability.
Start with ID, then try Name or CSS Selector, and finally use XPath for tough cases.
With practice, you’ll master finding any web element with ease!
Comments
Post a Comment