What are Locators in Selenium?
Locators are one of the most important concepts in Selenium WebDriver. A locator is a mechanism used by Selenium to identify and locate a specific web element on a web page so that the automation script can interact with it.
Web applications contain many elements such as text boxes, buttons, links, checkboxes, radio buttons, dropdowns, images, forms, tables, and menus. Selenium needs a reliable way to identify these elements before performing actions such as click(), sendKeys(), clear(), getText(), or getAttribute().
For example, if an application contains a Login button, Selenium first needs to locate that button and then perform the click operation.
driver.findElement(By.id("login")).click();
Here, By.id("login") is the locator strategy and Selenium uses it to identify the Login element.
Locators are a core part of Selenium WebDriver automation and are used along with Web Elements, browser automation, forms, buttons, dropdowns, navigation, waits, dynamic elements, and framework development.
For structured Selenium automation learning, you can explore the JustAcademy's Selenium Training Course and use the Register for Course Demo option.
1. What is a Locator?
A locator is an address or identification strategy used by Selenium WebDriver to find a particular element in the HTML DOM of a web page.
In simple words:
Locator = Way to identify a web element
For example:
WebElement username = driver.findElement(
By.id("username")
);
In this example:
WebElement represents the web element.
driver.findElement() searches for the element.
By.id() specifies the locator strategy.
"username" is the locator value.
2. Why Are Locators Important in Selenium?
Selenium cannot interact with a web element unless it can identify that element. Therefore, locators are essential for almost every Selenium automation script.
Locators are used to:
- Find text fields
- Find buttons
- Find links
- Find checkboxes
- Find radio buttons
- Find dropdowns
- Find images
- Find tables
- Find menus
- Find dynamic elements
- Find elements inside forms
- Find elements inside iframes
- Find elements inside complex page structures
3. Basic Selenium Locator Syntax
The most common syntax for locating an element is:
driver.findElement(By.locatorStrategy("locatorValue"));
Example:
driver.findElement(By.id("username"));
Another example:
driver.findElement(
By.xpath("//input[@name='email']")
);
4. Selenium Locator Strategies
Selenium WebDriver provides several locator strategies for identifying elements.
| Locator | Method | Example |
| ID | By.id() | By.id("username") |
| Name | By.name() | By.name("email") |
| Class Name | By.className() | By.className("login-btn") |
| Tag Name | By.tagName() | By.tagName("input") |
| Link Text | By.linkText() | By.linkText("Login") |
| Partial Link Text | By.partialLinkText() | By.partialLinkText("Log") |
| CSS Selector | By.cssSelector() | By.cssSelector("#username") |
| XPath | By.xpath() | By.xpath("//input[@id='username']") |
5. ID Locator
The ID locator identifies an element using its HTML id attribute.
Example HTML:
<input type="text" id="username">
Selenium code:
WebElement username = driver.findElement(
By.id("username")
);
To enter text:
driver.findElement(
By.id("username")
).sendKeys("admin");
6. Advantages of ID Locator
- Simple syntax
- Easy to understand
- Usually fast
- Easy to maintain
- Usually reliable when the ID is unique and stable
7. Disadvantages of ID Locator
- The page may not provide an ID.
- The ID may not be unique.
- The ID may be dynamically generated.
- The ID may change between sessions or page loads.
8. Name Locator
The name locator identifies an element using the HTML name attribute.
Example:
<input type="text" name="username">
Selenium:
driver.findElement(
By.name("username")
).sendKeys("admin");
9. When to Use Name Locator
Name locator is useful when:
- The element has a stable name attribute.
- The name value is unique.
- An ID is unavailable.
- The name value is easier to maintain than a complex XPath.
10. Class Name Locator
The class name locator identifies an element using the HTML class attribute.
<button class="login-button">
Login
</button>
Selenium:
driver.findElement(
By.className("login-button")
).click();
11. Important Rule for Class Name
When an element contains multiple classes, By.className() should be given a single class name rather than the complete space-separated class attribute.
For example:
<button class="btn btn-primary login-btn">
Login
</button>
Correct:
By.className("login-btn")
Incorrect:
By.className("btn btn-primary login-btn")
12. Tag Name Locator
Tag name identifies an element using its HTML tag.
driver.findElement(
By.tagName("input")
);
Common tag names include:
input
button
a
select
textarea
img
table
div
13. Finding Multiple Elements Using Tag Name
findElements() can be used when multiple elements need to be retrieved.
List<WebElement> links =
driver.findElements(By.tagName("a"));
System.out.println(
"Total links: " + links.size()
);
14. Link Text Locator
linkText() is specifically used for locating links using their complete visible text.
HTML:
<a href="/login">Login</a>
Selenium:
driver.findElement(
By.linkText("Login")
).click();
15. Partial Link Text Locator
partialLinkText() locates a link using a portion of its visible text.
HTML:
<a href="/registration">
Create New Account
</a>
Selenium:
driver.findElement(
By.partialLinkText("Create")
).click();
16. Difference Between linkText and partialLinkText
| Feature | linkText | partialLinkText |
| Matching | Complete text | Partial text |
| Precision | Usually higher | Can be less precise |
| Usage | Stable complete text | Known portion of text |
| Risk | Breaks if text changes | May match multiple links |
17. CSS Selector
CSS Selector is a powerful locator strategy that uses CSS syntax to identify elements.
driver.findElement(
By.cssSelector("#username")
);
CSS selectors can identify elements using:
- ID
- Class
- Attributes
- Multiple attributes
- Parent-child relationships
- Attribute values
18. CSS Selector Using ID
CSS uses # to represent an ID.
By.cssSelector("#username")
Equivalent XPath:
By.xpath("//input[@id='username']")
19. CSS Selector Using Class
CSS uses . to represent a class.
By.cssSelector(".login-button")
HTML:
<button class="login-button">
Login
</button>
20. CSS Selector Using Tag and Class
By.cssSelector("button.login-button")
This means find a button element having the class login-button.
21. CSS Selector Using Attribute
By.cssSelector(
"input[name='username']"
)
HTML:
<input name="username">
22. CSS Selector Using Multiple Attributes
By.cssSelector(
"input[type='text'][name='username']"
)
Multiple attributes can make a locator more specific.
23. CSS Selector Contains Attribute
The *= operator checks whether an attribute contains a specified value.
By.cssSelector(
"input[id*='user']"
)
24. CSS Selector Starts With
The ^= operator checks whether an attribute starts with a specified value.
By.cssSelector(
"input[id^='user']"
)
25. CSS Selector Ends With
The $= operator checks whether an attribute ends with a specified value.
By.cssSelector(
"input[id$='name']"
)
26. CSS Selector Parent-Child Relationship
By.cssSelector(
"form.login-form input"
)
This finds an input element inside an element having the login-form class.
27. XPath Locator
XPath is a query language used to navigate and locate elements in an HTML or XML document. Selenium supports XPath as one of its most powerful locator strategies.
driver.findElement(
By.xpath("//input[@id='username']")
);
28. Absolute XPath
Absolute XPath starts from the root of the HTML document.
/html/body/div/form/input
Absolute XPath is generally fragile because any structural change in the page can break the locator.
29. Relative XPath
Relative XPath generally starts with // and identifies elements based on attributes or relationships.
//input[@id='username']
Relative XPath is usually preferred over long absolute XPath expressions.
30. XPath Using ID
By.xpath("//input[@id='username']")
31. XPath Using Name
By.xpath("//input[@name='username']")
32. XPath Using Class
By.xpath(
"//button[@class='login-button']"
)
33. XPath Using Multiple Attributes
By.xpath(
"//input[@type='text' and @name='username']"
)
34. XPath Using Text
The text() function can identify an element based on its visible text.
By.xpath(
"//button[text()='Login']"
)
35. XPath Using contains()
contains() is useful when an attribute or text contains a stable portion of the value.
By.xpath(
"//input[contains(@id,'user')]"
)
Example:
<input id="user_12345">
36. XPath contains() with Text
By.xpath(
"//button[contains(text(),'Login')]"
)
37. XPath starts-with()
starts-with() is useful when the beginning of an attribute value is stable.
By.xpath(
"//input[starts-with(@id,'user_')]"
)
38. XPath and Operator
The and operator allows multiple conditions.
By.xpath(
"//input[@type='text' and @name='username']"
)
39. XPath or Operator
The or operator allows alternative conditions.
By.xpath(
"//input[@id='username' or @name='username']"
)
40. XPath Parent Relationship
By.xpath(
"//label[text()='Username']/parent::div"
)
41. XPath Child Relationship
By.xpath(
"//div[@class='login-form']/child::input"
)
42. XPath Descendant Relationship
By.xpath(
"//form[@id='loginForm']//input"
)
43. XPath Following-Sibling
By.xpath(
"//label[text()='Username']/following-sibling::input"
)
44. XPath Following
By.xpath(
"//label[text()='Username']/following::input[1]"
)
45. XPath Preceding
By.xpath(
"//input[@id='password']/preceding::label[1]"
)
46. XPath Index
An index can be used when multiple elements match the same XPath.
By.xpath("(//input[@type='text'])[2]")
Index-based locators should be used carefully because page structure changes can change element positions.
47. XPath normalize-space()
normalize-space() can help when visible text contains unwanted leading, trailing, or repeated whitespace.
By.xpath(
"//button[normalize-space()='Login']"
)
48. XPath starts-with() and contains()
By.xpath(
"//input[starts-with(@id,'user') and contains(@class,'field')]"
)
49. XPath Dynamic Element
Modern applications often generate dynamic IDs such as:
user_483920
user_728391
user_918273
Instead of using the complete dynamic value, use a stable portion:
By.xpath(
"//input[starts-with(@id,'user_')]"
)
50. Choosing the Right Locator
| Situation | Recommended Locator |
| Unique stable ID | ID |
| Stable name attribute | Name |
| Stable class | Class Name or CSS |
| Link with stable text | Link Text |
| Partially known link text | Partial Link Text |
| Simple attribute selection | CSS Selector |
| Complex relationship | XPath |
| Dynamic attributes | CSS or XPath with stable portions |
51. Locator Priority
There is no universal ranking that guarantees one locator is always the best. The practical goal is to choose a locator that is unique, stable, readable, and resistant to expected UI changes.
A practical preference is:
- Stable unique ID
- Stable meaningful name or data attribute
- Stable CSS selector
- Link text for stable links
- Relative XPath for complex relationships
52. Unique Locator
A good locator should identify the intended element without accidentally matching unrelated elements.
By.id("username")
If the ID is unique and stable, this is usually straightforward.
53. Duplicate Locator
Sometimes the same locator identifies multiple elements.
List<WebElement> buttons =
driver.findElements(
By.className("btn")
);
System.out.println(
buttons.size()
);
When multiple elements match, a more specific locator may be required.
54. findElement() vs findElements()
| Method | Return Type | Purpose |
findElement() | WebElement | Find one matching element |
findElements() | List<WebElement> | Find all matching elements |
55. findElement() Example
WebElement username =
driver.findElement(
By.id("username")
);
56. findElements() Example
List<WebElement> links =
driver.findElements(
By.tagName("a")
);
57. What Happens When findElement() Cannot Find an Element?
If Selenium cannot find an element using findElement(), it generally throws NoSuchElementException.
WebElement element =
driver.findElement(
By.id("incorrectId")
);
If the element does not exist, Selenium reports a NoSuchElementException.
58. What Happens When findElements() Cannot Find an Element?
findElements() generally returns an empty list when no matching elements are found.
List<WebElement> elements =
driver.findElements(
By.className("missing")
);
System.out.println(
elements.size()
);
59. Locator and WebElement
A locator identifies an element, while WebElement represents the element returned by Selenium.
By usernameLocator =
By.id("username");
WebElement username =
driver.findElement(
usernameLocator
);
username.sendKeys("admin");
60. Locator and Selenium Actions
After locating an element, Selenium can perform various operations.
| Action | Method |
| Click | click() |
| Enter text | sendKeys() |
| Clear text | clear() |
| Get visible text | getText() |
| Get attribute | getAttribute() |
| Check visibility | isDisplayed() |
| Check enabled state | isEnabled() |
| Check selection | isSelected() |
61. Locating a Text Field
WebElement username =
driver.findElement(
By.id("username")
);
username.sendKeys("admin");
62. Locating a Password Field
driver.findElement(
By.name("password")
).sendKeys("secret123");
63. Locating a Button
driver.findElement(
By.id("loginButton")
).click();
64. Locating a Checkbox
driver.findElement(
By.id("rememberMe")
).click();
65. Locating a Radio Button
driver.findElement(
By.cssSelector(
"input[value='male']"
)
).click();
66. Locating a Dropdown
WebElement country =
driver.findElement(
By.id("country")
);
67. Locating a Link
driver.findElement(
By.linkText("About Us")
).click();
68. Locating an Image
WebElement image =
driver.findElement(
By.cssSelector("img.logo")
);
69. Locating a Table
WebElement table =
driver.findElement(
By.id("employeeTable")
);
70. Locating a Form
WebElement form =
driver.findElement(
By.id("registrationForm")
);
71. Locating Elements Using data-* Attributes
Modern applications frequently provide stable custom attributes such as data-testid, data-id, or data-qa specifically for testing and automation.
<button data-testid="login-button">
Login
</button>
CSS:
By.cssSelector(
"[data-testid='login-button']"
)
XPath:
By.xpath(
"//button[@data-testid='login-button']"
)
72. Why data-testid Attributes Are Useful
- They can provide stable automation hooks.
- They reduce dependency on presentation-related CSS classes.
- They can make tests easier to maintain.
- They can distinguish elements that have similar visible text.
73. Dynamic Class Locator
Some applications generate classes dynamically.
button-Mx82Qa
button-Ap91Lm
button-Xz72Rt
Instead of depending on the complete class, look for a stable attribute or stable class portion.
By.cssSelector(
"button[class*='button-']"
)
74. Dynamic ID Locator
For dynamic IDs:
user_83921
user_47291
user_58372
Use:
By.xpath(
"//input[starts-with(@id,'user_')]"
)
75. Handling Dynamic Text
If the visible text changes but contains a stable word, contains() can be useful.
By.xpath(
"//button[contains(text(),'Submit')]"
)
76. Locator for Dynamic Product
By.xpath(
"//div[contains(@class,'product')]//a[contains(text(),'Laptop')]"
)
77. Locator Inside a Specific Section
When multiple elements have similar attributes, first identify a unique parent and then search inside it.
WebElement loginForm =
driver.findElement(
By.id("loginForm")
);
WebElement username =
loginForm.findElement(
By.name("username")
);
78. Locator Inside a Table Row
WebElement row =
driver.findElement(
By.xpath(
"//tr[td[text()='John']]"
)
);
WebElement edit =
row.findElement(
By.linkText("Edit")
);
edit.click();
79. Locator Inside a Modal
WebElement modal =
driver.findElement(
By.id("loginModal")
);
modal.findElement(
By.id("username")
).sendKeys("admin");
80. Locator Inside an iframe
Selenium must switch to the appropriate iframe before locating an element inside it.
driver.switchTo().frame("loginFrame");
driver.findElement(
By.id("username")
).sendKeys("admin");
driver.switchTo().defaultContent();
81. Locator Inside Nested Iframes
driver.switchTo().frame("outerFrame");
driver.switchTo().frame("innerFrame");
driver.findElement(
By.id("username")
).sendKeys("admin");
driver.switchTo().defaultContent();
82. Locator Inside Shadow DOM
Modern web applications may use Shadow DOM to encapsulate elements.
WebElement host =
driver.findElement(
By.cssSelector("custom-login")
);
SearchContext shadowRoot =
host.getShadowRoot();
WebElement username =
shadowRoot.findElement(
By.cssSelector("#username")
);
83. Explicit Wait with Locator
Explicit waits commonly receive a locator and wait until a specific condition is satisfied.
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement login =
wait.until(
ExpectedConditions.elementToBeClickable(
By.id("login")
)
);
login.click();
84. Visibility Wait with Locator
WebElement username =
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("username")
)
);
85. Presence Wait with Locator
WebElement element =
wait.until(
ExpectedConditions.presenceOfElementLocated(
By.id("username")
)
);
86. Locator and Page Object Model
In Page Object Model, locators are generally stored as page-level fields so that page interaction logic remains organized and maintainable.
public class LoginPage {
WebDriver driver;
By username =
By.id("username");
By password =
By.id("password");
By loginButton =
By.id("login");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void enterUsername(String value) {
driver.findElement(username)
.sendKeys(value);
}
public void enterPassword(String value) {
driver.findElement(password)
.sendKeys(value);
}
public void clickLogin() {
driver.findElement(loginButton)
.click();
}
}
87. Why Store Locators in Page Objects?
- Improves code organization
- Reduces duplication
- Makes maintenance easier
- Keeps page structure separate from test logic
- Allows locators to be updated in one place
88. Locator Reusability
A locator can be declared once and reused multiple times.
By usernameLocator =
By.id("username");
driver.findElement(
usernameLocator
).sendKeys("admin");
driver.findElement(
usernameLocator
).clear();
driver.findElement(
usernameLocator
).sendKeys("testuser");
89. Reusable Locator Utility
public WebElement find(
WebDriver driver,
By locator) {
return driver.findElement(locator);
}
Usage:
WebElement username =
find(
driver,
By.id("username")
);
90. Locator Utility with Explicit Wait
public WebElement waitForElement(
WebDriver driver,
By locator) {
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
return wait.until(
ExpectedConditions.visibilityOfElementLocated(
locator
)
);
}
91. Common Locator Mistakes
- Using unstable dynamic IDs
- Using long absolute XPath
- Using indexes unnecessarily
- Using duplicate class names without additional conditions
- Using partial link text when multiple links match
- Ignoring iframe context
- Ignoring Shadow DOM
- Not waiting for dynamic elements
- Using brittle locators tied to layout
- Not validating locator uniqueness
92. Bad Absolute XPath
/html/body/div[2]/div[1]/form/div[2]/input[1]
This type of XPath is fragile because changes in the DOM hierarchy can break the locator.
93. Better Relative XPath
//input[@id='username']
A relative XPath based on a stable attribute is generally easier to maintain.
94. Bad Index-Based Locator
(//button)[8]
This may work temporarily but can fail when another button is added before the eighth button.
95. Better Attribute-Based Locator
//button[@id='submitButton']
96. Locator Uniqueness Check
A locator should ideally identify the intended element uniquely.
List<WebElement> elements =
driver.findElements(
By.cssSelector("#username")
);
System.out.println(
"Matching elements: " +
elements.size()
);
If a locator expected to identify one element returns many matches, it should be made more specific.
97. Locator Stability
Locator stability refers to how well a locator continues to work when the application changes.
| Locator Type | Potential Stability |
| Stable ID | High |
| Stable data-testid | High |
| Stable name | High |
| Stable CSS | High |
| Visible text | Depends on content changes |
| Dynamic class | Low |
| Absolute XPath | Low |
| Position-only XPath | Low |
98. Locator Readability
A good locator should be understandable to another tester or developer.
Less readable:
//div[3]/div[2]/button[1]
More readable:
//button[@id='loginButton']
99. Locator Maintainability
Maintainable locators are based on attributes or relationships that are unlikely to change unnecessarily.
- Use stable IDs.
- Use dedicated test attributes when available.
- Avoid styling-only classes.
- Avoid deep DOM traversal.
- Avoid unnecessary positional indexes.
- Use meaningful page objects.
100. Locator and Dynamic Web Applications
Modern applications frequently use React, Angular, Vue, AJAX, dynamic components, asynchronous rendering, and generated attributes. Because of this, locator design is especially important.
For dynamic applications:
- Identify stable attributes.
- Use relative XPath when necessary.
- Use CSS attribute selectors.
- Use explicit waits.
- Avoid generated IDs when they are unstable.
- Use application-provided test attributes when available.
101. React Application Locator Example
<button data-testid="login-button">
Login
</button>
Selenium:
driver.findElement(
By.cssSelector(
"[data-testid='login-button']"
)
).click();
102. Angular Application Locator Example
Angular applications can expose attributes and classes that may be useful for locating elements, but testers should prefer stable application attributes over framework-specific implementation details.
driver.findElement(
By.cssSelector(
"input[name='username']"
)
).sendKeys("admin");
103. Locator with aria-label
Accessibility attributes such as aria-label can sometimes provide useful and meaningful locator values.
<button aria-label="Search">
<span>🔍</span>
</button>
CSS:
driver.findElement(
By.cssSelector(
"button[aria-label='Search']"
)
).click();
104. Locator Using Placeholder
<input
type="text"
placeholder="Enter username">
driver.findElement(
By.cssSelector(
"input[placeholder='Enter username']"
)
).sendKeys("admin");
105. Locator Using Value Attribute
<input
type="radio"
value="male">
driver.findElement(
By.cssSelector(
"input[value='male']"
)
).click();
106. Locator Using Type Attribute
driver.findElement(
By.cssSelector(
"input[type='password']"
)
);
107. Locator Using Multiple Conditions
driver.findElement(
By.cssSelector(
"input[type='text'][name='username']"
)
);
108. Locator Strategy for Login Page
| Element | Example Locator |
| Username | By.id("username") |
| Password | By.id("password") |
| Login button | By.id("loginButton") |
| Forgot password | By.linkText("Forgot Password") |
| Remember checkbox | By.id("rememberMe") |
109. Complete Login Example
driver.findElement(
By.id("username")
).sendKeys("admin");
driver.findElement(
By.id("password")
).sendKeys("admin123");
driver.findElement(
By.id("loginButton")
).click();
110. Locator Strategy for Registration Page
| Element | Locator Example |
| First Name | By.name("firstName") |
| Last Name | By.name("lastName") |
| Email | By.id("email") |
| Password | By.id("password") |
| Country | By.id("country") |
| Register button | By.cssSelector("button[type='submit']") |
111. Locator Strategy for E-Commerce Page
| Element | Locator Example |
| Search box | By.id("search") |
| Search button | By.cssSelector("button.search") |
| Product link | By.xpath("//a[contains(text(),'Laptop')]") |
| Add to cart | By.id("addToCart") |
| Cart link | By.linkText("Cart") |
112. Locator Strategy for a Table
WebElement row =
driver.findElement(
By.xpath(
"//tr[td[text()='John']]"
)
);
WebElement edit =
row.findElement(
By.linkText("Edit")
);
edit.click();
113. Locator Strategy for Dynamic Tables
driver.findElement(
By.xpath(
"//table[@id='users']//tr" +
"[td[contains(text(),'John')]]" +
"//button[contains(text(),'Edit')]"
)
).click();
114. Locator Strategy for Dropdown Options
driver.findElement(
By.xpath(
"//select[@id='country']" +
"//option[text()='India']"
)
).click();
115. Locator Strategy for Radio Buttons
driver.findElement(
By.cssSelector(
"input[name='gender'][value='male']"
)
).click();
116. Locator Strategy for Checkboxes
driver.findElement(
By.cssSelector(
"input[name='terms']"
)
).click();
117. Locator Strategy for Search Results
driver.findElement(
By.xpath(
"//div[contains(@class,'search-result')]" +
"//a[contains(text(),'Selenium')]"
)
).click();
118. Locator Strategy for Navigation Menu
driver.findElement(
By.xpath(
"//nav//a[text()='Products']"
)
).click();
119. Locator Strategy for Footer
driver.findElement(
By.xpath(
"//footer//a[text()='Privacy Policy']"
)
).click();
120. Locator Strategy for Modal
WebElement modal =
driver.findElement(
By.cssSelector(".modal")
);
modal.findElement(
By.cssSelector(
"button[type='submit']"
)
).click();
121. Locator Strategy with Explicit Wait
By loginButton =
By.id("loginButton");
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement button =
wait.until(
ExpectedConditions.elementToBeClickable(
loginButton
)
);
button.click();
122. Locator Strategy and TestNG
@Test
public void verifyLoginButton() {
WebElement button =
driver.findElement(
By.id("loginButton")
);
Assert.assertTrue(
button.isDisplayed()
);
Assert.assertTrue(
button.isEnabled()
);
}
123. Locator Strategy in Page Object Model
public class LoginPage {
private WebDriver driver;
private By username =
By.id("username");
private By password =
By.id("password");
private By login =
By.id("loginButton");
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void login(
String user,
String pass) {
driver.findElement(username)
.sendKeys(user);
driver.findElement(password)
.sendKeys(pass);
driver.findElement(login)
.click();
}
}
124. Locator Debugging
When a locator fails, follow a systematic debugging process.
- Inspect the element in browser developer tools.
- Check the tag name.
- Check the ID.
- Check the name attribute.
- Check classes.
- Check custom data attributes.
- Check the element hierarchy.
- Test the CSS selector or XPath.
- Check whether the element is inside an iframe.
- Check whether the element is inside Shadow DOM.
- Check whether the element loads dynamically.
- Add an appropriate explicit wait.
125. Best Practices for Selenium Locators
- Prefer unique and stable locators.
- Use stable IDs when available.
- Use dedicated testing attributes such as
data-testid when provided.
- Use CSS selectors for simple attribute-based identification.
- Use relative XPath for complex relationships.
- Avoid absolute XPath whenever possible.
- Avoid unnecessary positional indexes.
- Avoid unstable dynamically generated attributes.
- Use link text only when link text is stable.
- Use partial link text only when it uniquely identifies the link.
- Validate that the locator identifies the intended element.
- Use explicit waits for dynamically rendered elements.
- Keep locators centralized in Page Objects or another maintainable structure.
- Do not use JavaScript just to bypass a locator or synchronization problem.
126. Common Interview Questions on Locators
Q1. What is a locator in Selenium?
A locator is a strategy used by Selenium WebDriver to identify a specific web element in the DOM so that the automation script can interact with it.
Q2. How many standard locator strategies are available in Selenium?
Selenium provides eight commonly used locator strategies: ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath.
Q3. Which locator can be used for links?
linkText() and partialLinkText() are specifically designed for links. CSS and XPath can also locate links.
Q4. What is the difference between findElement() and findElements()?
findElement() returns one matching WebElement and throws an exception when no matching element is found. findElements() returns a list and generally returns an empty list when there are no matches.
Q5. What is the difference between absolute and relative XPath?
Absolute XPath starts from the root of the document and usually depends heavily on DOM structure. Relative XPath generally starts with // and identifies elements through attributes, text, or relationships.
Q6. What is the purpose of contains() in XPath?
contains() is used when only part of an attribute value or text is stable.
Q7. What is the purpose of starts-with()?
starts-with() identifies elements where an attribute or string begins with a specified value.
Q8. Which is better, CSS or XPath?
Neither is universally better. The appropriate choice depends on the application's DOM, locator stability, readability, and the relationship needed to identify the element.
Q9. Why should absolute XPath be avoided?
Absolute XPath is highly dependent on the exact DOM hierarchy. Small structural changes can cause it to fail.
Q10. How do you handle dynamic IDs?
Use a stable attribute or a dynamic XPath/CSS expression that targets the stable portion of the value, such as starts-with(), contains(), or CSS attribute matching.
127. Practical Project: Selenium Login Automation
Create a complete Selenium login automation test using appropriate locators.
Test flow:
- Open the application.
- Locate username field.
- Enter username.
- Locate password field.
- Enter password.
- Locate the Login button.
- Click Login.
- Wait for successful navigation.
- Verify the dashboard URL.
- Verify the dashboard heading.
driver.get("https://example.com/login");
driver.findElement(
By.id("username")
).sendKeys("admin");
driver.findElement(
By.id("password")
).sendKeys("admin123");
driver.findElement(
By.id("loginButton")
).click();
WebDriverWait wait =
new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
wait.until(
ExpectedConditions.urlContains(
"/dashboard"
)
);
Assert.assertTrue(
driver.getCurrentUrl()
.contains("/dashboard")
);
128. Practical Project: Registration Automation
Create a registration automation project using multiple locator strategies.
driver.findElement(
By.name("firstName")
).sendKeys("John");
driver.findElement(
By.name("lastName")
).sendKeys("Doe");
driver.findElement(
By.id("email")
).sendKeys("[email protected]");
driver.findElement(
By.cssSelector(
"input[name='terms']"
)
).click();
driver.findElement(
By.xpath(
"//button[text()='Register']"
)
).click();
129. Practical Project: E-Commerce Automation
Automate an e-commerce website using different locator strategies.
- Locate the search box using ID.
- Locate the search button using CSS.
- Locate a product using XPath.
- Locate Add to Cart using ID.
- Locate Cart using link text.
- Locate Checkout using CSS or XPath.
driver.findElement(
By.id("search")
).sendKeys("Laptop");
driver.findElement(
By.cssSelector("button.search")
).click();
driver.findElement(
By.xpath(
"//a[contains(text(),'Laptop')]"
)
).click();
driver.findElement(
By.id("addToCart")
).click();
driver.findElement(
By.linkText("Cart")
).click();
130. Locator Strategy Summary
| Locator | Syntax | Best Use |
| ID | By.id() | Unique stable ID |
| Name | By.name() | Stable name attribute |
| Class Name | By.className() | Unique stable class |
| Tag Name | By.tagName() | Finding elements by tag |
| Link Text | By.linkText() | Exact link text |
| Partial Link Text | By.partialLinkText() | Partial link text |
| CSS Selector | By.cssSelector() | Flexible CSS-based identification |
| XPath | By.xpath() | Complex relationships and dynamic elements |
131. Final Locator Checklist
- Understand the HTML structure before creating a locator.
- Inspect the element using browser developer tools.
- Look for a unique stable ID first.
- Check for stable name or testing attributes.
- Use CSS selectors for simple attribute-based locators.
- Use XPath for complex relationships.
- Avoid absolute XPath.
- Avoid unnecessary indexes.
- Check locator uniqueness.
- Handle dynamic attributes carefully.
- Use explicit waits for dynamic elements.
- Consider iframe and Shadow DOM boundaries.
- Keep locators maintainable.
- Store reusable locators in Page Object classes.
- Validate the actual element before performing actions.
132. Conclusion
Locators are the foundation of Selenium WebDriver automation. Selenium uses locators to identify web elements before performing actions such as clicking, entering text, selecting options, checking states, reading text, and validating application behavior.
The major Selenium locator strategies are ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, CSS Selector, and XPath. Selecting the appropriate locator depends on the HTML structure, stability of attributes, uniqueness, readability, and maintainability of the automation script.
For modern dynamic applications, testers should understand CSS selectors, XPath functions such as contains() and starts-with(), custom test attributes, explicit waits, iframe handling, Shadow DOM, and Page Object Model. A well-designed locator strategy makes Selenium automation more stable, readable, reusable, and easier to maintain.
For comprehensive Selenium automation training covering WebDriver, locators, Web Elements, forms, dropdowns, waits, TestNG, Page Object Model, frameworks, cross-browser testing, reporting, CI/CD, and real-time projects, visit the JustAcademy's Selenium Training Course.
To register for a course demo, visit the Register for Course Demo page.