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