What Are Locators?
Locators are used to identify web elements on a web page.
In Selenium WebDriver, elements are located using:
findElement()findElements()
Locators are broadly classified into two categories.
Types of Locators
Attribute-Based Locators
Attribute-based locators identify elements using their HTML attributes.
Examples include:
- Id
- Name
- LinkText
- PartialLinkText
- ClassName
- TagName
Structure-Based Locators
Structure-based locators identify elements based on the structure of the DOM (Document Object Model).
Examples include:
- XPath
- CSS Selector
The By Abstract Class
Selenium WebDriver provides an abstract class called By.
The By class contains static methods used to locate web elements.
Common methods include:
By.id()
By.name()
By.tagName()
By.linkText()
By.partialLinkText()
By.className()
By.cssSelector()
By.xpath()
CSS Selectors
CSS Selectors are string patterns used to identify web elements.
They locate elements based on combinations of:
- HTML tag
- ID
- Class
- Attributes
CSS Selectors are widely used because they can locate elements even when they do not have an ID or Name.
CSS Selector Syntax
Tag and ID
Syntax:
tag#id
The # symbol is used before the ID.
Example:
input#username
Tag and Class
Syntax:
tag.class
The . (dot) is used before the class name.
Example:
input.form-control
Tag and Attribute
Syntax:
tag[attribute=value]
Example:
input[name='email']
Prefer using attributes that uniquely identify the element.
Tag, Class and Attribute
Syntax:
tag.class[attribute=value]
Example:
input.form-control[type='text']
Inner Text
HTML labels often do not have IDs or Names.
They can be accessed using their visible text.
Syntax:
tag:contains("inner text")
What is XPath?
XPath (XML Path Language) is a syntax used to locate elements in XML and HTML documents.
In Selenium, XPath identifies elements using:
- Attributes
- Text
- Hierarchy
- DOM structure
Types of XPath
There are two types of XPath.
Absolute XPath
Absolute XPath starts from the root node (html) and follows the complete hierarchy to the target element.
Example:
/html/body/div/form/input
Relative XPath
Relative XPath starts from any node in the document.
It begins with:
//
Relative XPath is:
- Shorter
- Flexible
- More reliable
Example:
//form/input[1]
Absolute XPath vs Relative XPath
Absolute XPath
- Starts from the root node.
- Uses the complete DOM hierarchy.
- Long and difficult to maintain.
- Breaks easily when the page structure changes.
Relative XPath
- Starts from anywhere in the DOM.
- Uses
//. - Shorter.
- Flexible.
- More reliable.
- Preferred in real projects.
Relative XPath is generally faster than Absolute XPath.
Interview Point
I mostly use Relative XPath in real projects because it is less likely to break when the page structure changes.
XPath Axes
XPath Axes are keywords used to navigate between related elements in the DOM.
They locate elements based on relationships.
child::
Locates direct child elements.
Family analogy:
Your children.
parent::
Locates the parent element.
Family analogy:
Your parents.
following-sibling::
Locates younger sibling elements.
Family analogy:
Your younger brothers or sisters.
preceding-sibling::
Locates elder sibling elements.
Family analogy:
Your older brothers or sisters.
ancestor::
Locates parent, grandparent, and higher-level ancestors.
Family analogy:
Your grandparents.
descendant::
Locates all child and grandchild elements.
Family analogy:
Your grandchildren.
self::
Locates the current element itself.
Family analogy:
You.
following::
Locates all elements appearing after the current element.
preceding::
Locates all elements appearing before the current element.
When Should XPath Axes Be Used?
XPath Axes are useful when:
- Elements have no unique ID.
- Attributes change dynamically.
- Elements are deeply nested.
Example:
Use:
ancestor::following-sibling::
to locate nearby stable elements.
Interview Point
In one project, I used
ancestor::trandfollowing-sibling::tdto locate the correct table cell.
Common XPath Questions
Why not always use ID?
ID is the best locator.
However, many applications do not provide unique IDs.
XPath Axes provide context-based locating.
Can multiple axes be combined?
Yes.
Multiple XPath axes can be chained together.
child vs descendant
child
Returns only direct children.
descendant
Returns children, grandchildren, and all lower-level descendants.
Commonly Used Axes
- parent
- child
- ancestor
- descendant
- following-sibling
These create robust XPath expressions.
XPath Axes and Double Colon (::)
XPath axes use the double colon operator.
Example:
//*[@type='text']//following::input
//*[@type='text']//following::input[1]
Example:
//div[@class='parent']//following-sibling::div
Here:
following-sibling→ XPath Axisdiv→ Node Test
The :: operator separates the axis from the node.
Methods Used Along with XPath
findElement()
Locates the first matching element.
findElement(By.xpath("expression"))
findElements()
Locates all matching elements.
Returns a List<WebElement>.
findElements(By.xpath("expression"))
getText()
Returns the visible text of an element.
getText()
getAttribute()
Returns the value of an attribute.
getAttribute("attributeName")
sendKeys()
Enters text into an input field.
sendKeys("text")
click()
Performs a mouse click.
click()
isDisplayed()
Checks whether the element is visible.
isDisplayed()
isEnabled()
Checks whether the element is enabled.
isEnabled()
Locating Dynamic Elements
Dynamic elements change their properties at runtime.
Examples:
- Dynamic ID
- Dynamic Class
- Dynamic Name
These make automation more challenging.
Strategy 1 – XPath Functions
Use XPath functions such as:
contains()starts-with()ends-with()
to match partial attribute values.
Strategy 2 – CSS Selectors
Use CSS attribute selectors that match partial values of IDs or classes.
Strategy 3 – Use Relationships
Locate nearby stable elements and use XPath Axes such as:
- parent
- ancestor
- following-sibling
to reach the target element.
Handling Duplicate IDs
Sometimes two elements may have the same ID.
Although duplicate IDs violate HTML standards, they can exist.
In such cases:
Do not rely on:
By.id()
Instead use:
- XPath
- CSS Selector
- Name
- ClassName
Using Indexing
Example:
(//input[@id='duplicateId'])[2]
This selects the second matching element.
Using Context
Locate the element relative to:
- Parent
- Child
- Sibling
- Nearby label
This makes the locator more reliable.
FAQs
1. What are Locators in Selenium?
Locators identify web elements on a page.
They are classified as:
- Attribute-Based Locators
- Structure-Based Locators
2. What is the By Class?
The By class is an abstract Selenium class that provides static methods such as:
By.id()By.name()By.xpath()By.cssSelector()
to locate web elements.
3. What is the CSS Selector Syntax?
Common CSS Selector syntax includes:
tag#idtag.classtag[attribute=value]tag.class[attribute=value]tag:contains("inner text")
4. What are the two types of XPath?
- Absolute XPath
- Relative XPath
5. Which is faster: Absolute XPath or Relative XPath?
Relative XPath is generally faster.
It is also more flexible and less likely to break when the page structure changes.
6. What are XPath Axes?
XPath Axes navigate the DOM using relationships such as:
- parent
- child
- ancestor
- descendant
- following-sibling
- preceding-sibling
7. What does the :: operator mean in XPath?
The double colon separates the XPath Axis from the node.
Example:
following-sibling::div
8. How do you locate dynamic elements?
Dynamic elements can be located using:
contains()starts-with()ends-with()- CSS attribute selectors
- XPath Axes based on stable nearby elements
9. How do you handle duplicate IDs?
You can:
- Use XPath.
- Use CSS Selectors.
- Use indexing.
Example:
(//input[@id='duplicateId'])[2]
Or locate the element using its parent, sibling, or nearby stable elements.