Popular Searches
Popular Course Categories
Popular Courses

Name Locator

Selenium Locators

<div class="selenium-notes">

<h1>Name Locator in Selenium</h1>

<p>The <strong>Name Locator</strong> is one of the standard locator strategies provided by Selenium WebDriver for identifying web elements through the value of their HTML <code>name</code> attribute. It is commonly used for locating form fields such as username, password, email, search boxes, radio buttons, checkboxes, and other input elements.</p>

<p>In Selenium Java, the Name Locator is implemented using <code>By.name()</code>. For example, if an HTML element contains <code>name="username"</code>, Selenium can locate it using <code>driver.findElement(By.name("username"))</code>.</p>

<p>Locators are an important part of Selenium WebDriver because automation scripts need to identify the correct WebElement before performing actions such as <code>click()</code>, <code>sendKeys()</code>, <code>clear()</code>, <code>getText()</code>, or attribute validation. JustAcademy's Selenium training curriculum includes locating elements using strategies such as ID, XPath, and CSS selectors as part of Selenium WebDriver and WebElement automation. :contentReference[oaicite:0]{index=0}</p>

<p>Learn more through the <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">JustAcademy's Selenium Training Course</a> and explore the <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Selenium Course Demo Registration</a>.</p>

<hr>

<h2>1. What is a Name Locator?</h2>

<p>A Name Locator is a Selenium locator strategy that identifies a web element using the value of its HTML <code>name</code> attribute.</p>

<p>The basic Selenium Java syntax is:</p>

<pre><code>driver.findElement(By.name("elementName"));</code></pre>

<p>For example, consider this HTML:</p>

<pre><code>&lt;input type="text" name="username"&gt;</code></pre>

<p>The element can be located using:</p>

<pre><code>driver.findElement(By.name("username"));</code></pre>

<p>Here, <code>username</code> is the value of the <code>name</code> attribute.</p>

<hr>

<h2>2. Understanding the HTML name Attribute</h2>

<p>The <code>name</code> attribute is an HTML attribute commonly used to identify form controls and associate submitted form values with field names.</p>

<p>Example:</p>

<pre><code>&lt;input type="text" name="firstName"&gt;</code></pre>

<p>In this example:</p>

<ul>

<li><code>input</code> is the HTML element.</li>

<li><code>type</code> is an HTML attribute.</li>

<li><code>text</code> is the value of the type attribute.</li>

<li><code>name</code> is the attribute used by Selenium for the Name Locator.</li>

<li><code>firstName</code> is the name attribute value.</li>

</ul>

<hr>

<h2>3. Syntax of Name Locator</h2>

<p>The Selenium Java syntax for a Name Locator is:</p>

<pre><code>By.name("nameValue")</code></pre>

<p>It is generally used with <code>findElement()</code>:</p>

<pre><code>WebElement element = driver.findElement(By.name("nameValue"));</code></pre>

<p>For example:</p>

<pre><code>WebElement username = driver.findElement(By.name("username"));</code></pre>

<hr>

<h2>4. Simple Name Locator Example</h2>

<p>Suppose a web page contains the following input field:</p>

<pre><code>&lt;input type="text" name="username"&gt;</code></pre>

<p>Selenium code:</p>

<pre><code>driver.findElement(By.name("username")).sendKeys("admin");</code></pre>

<p>Selenium first searches for an element whose <code>name</code> attribute has the value <code>username</code> and then enters the specified text.</p>

<hr>

<h2>5. Name Locator with Username Field</h2>

<pre><code>&lt;input type="text" name="username" placeholder="Enter Username"&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("username")).sendKeys("john");</code></pre>

<hr>

<h2>6. Name Locator with Password Field</h2>

<pre><code>&lt;input type="password" name="password" placeholder="Enter Password"&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("password")).sendKeys("Pass@123");</code></pre>

<hr>

<h2>7. Name Locator with Email Field</h2>

<pre><code>&lt;input type="email" name="email"&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("email")).sendKeys("[email protected]");</code></pre>

<hr>

<h2>8. Name Locator with Search Box</h2>

<pre><code>&lt;input type="search" name="search"&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("search")).sendKeys("Selenium WebDriver");</code></pre>

<hr>

<h2>9. Name Locator with Button</h2>

<p>A button can also have a <code>name</code> attribute.</p>

<pre><code>&lt;button type="submit" name="login"&gt;Login&lt;/button&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("login")).click();</code></pre>

<hr>

<h2>10. Name Locator with Checkbox</h2>

<pre><code>&lt;input type="checkbox" name="terms" value="accepted"&gt;</code></pre>

<p>Selenium:</p>

<pre><code>WebElement terms = driver.findElement(By.name("terms"));

 

if (!terms.isSelected()) {

    terms.click();

}</code></pre>

<hr>

<h2>11. Name Locator with Radio Button</h2>

<pre><code>&lt;input type="radio" name="gender" value="male"&gt;

&lt;input type="radio" name="gender" value="female"&gt;</code></pre>

<p>Because both radio buttons belong to the same group, they can share the same <code>name</code>.</p>

<pre><code>List&lt;WebElement&gt; genderOptions = driver.findElements(By.name("gender"));</code></pre>

<hr>

<h2>12. Name Locator with Form Fields</h2>

<p>Name locators are particularly common in HTML forms.</p>

<pre><code>&lt;form&gt;

    &lt;input type="text" name="firstName"&gt;

    &lt;input type="text" name="lastName"&gt;

    &lt;input type="email" name="email"&gt;

    &lt;input type="password" name="password"&gt;

&lt;/form&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("lastName")).sendKeys("Smith");

driver.findElement(By.name("email")).sendKeys("[email protected]");

driver.findElement(By.name("password")).sendKeys("Pass@123");</code></pre>

<hr>

<h2>13. Name Locator with sendKeys()</h2>

<p>The <code>sendKeys()</code> method is used to enter text into an input element.</p>

<pre><code>driver.findElement(By.name("username")).sendKeys("admin");</code></pre>

<p>This is commonly used for username, email, password, address, search, and other text fields.</p>

<hr>

<h2>14. Name Locator with clear()</h2>

<p>The <code>clear()</code> method removes the existing value from a text input.</p>

<pre><code>driver.findElement(By.name("username")).clear();</code></pre>

<p>A common pattern is:</p>

<pre><code>WebElement username = driver.findElement(By.name("username"));

username.clear();

username.sendKeys("newUser");</code></pre>

<hr>

<h2>15. Name Locator with click()</h2>

<p>The <code>click()</code> method can be used when the located element is clickable.</p>

<pre><code>driver.findElement(By.name("login")).click();</code></pre>

<p>It can be used for buttons, checkboxes, radio buttons, links, and other interactive elements when their <code>name</code> attribute is suitable.</p>

<hr>

<h2>16. Name Locator with getText()</h2>

<p>The <code>getText()</code> method retrieves visible text from an element.</p>

<pre><code>String message = driver.findElement(By.name("message")).getText();

System.out.println(message);</code></pre>

<p>The element must have the corresponding <code>name</code> attribute.</p>

<hr>

<h2>17. Name Locator with getAttribute()</h2>

<p>The <code>getAttribute()</code> method can be used to retrieve attribute values.</p>

<pre><code>WebElement username = driver.findElement(By.name("username"));

 

String value = username.getAttribute("value");

System.out.println(value);</code></pre>

<hr>

<h2>18. Name Locator with WebElement</h2>

<p>The located element can be stored in a <code>WebElement</code> variable.</p>

<pre><code>WebElement emailField = driver.findElement(By.name("email"));

emailField.sendKeys("[email protected]");</code></pre>

<p>This approach is useful when the same element needs to be accessed multiple times.</p>

<hr>

<h2>19. Required Selenium Imports</h2>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;</code></pre>

<hr>

<h2>20. Complete Basic Name Locator Program</h2>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class NameLocatorExample {

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        driver.findElement(By.name("username")).sendKeys("admin");

        driver.findElement(By.name("password")).sendKeys("admin123");

        driver.findElement(By.name("login")).click();

 

        driver.quit();

    }

}</code></pre>

<hr>

<h2>21. Name Locator in Login Form</h2>

<p>Consider the following login form:</p>

<pre><code>&lt;form&gt;

    &lt;input type="text" name="username"&gt;

    &lt;input type="password" name="password"&gt;

    &lt;button type="submit" name="login"&gt;Login&lt;/button&gt;

&lt;/form&gt;</code></pre>

<p>Selenium automation:</p>

<pre><code>driver.findElement(By.name("username")).sendKeys("admin");

driver.findElement(By.name("password")).sendKeys("admin123");

driver.findElement(By.name("login")).click();</code></pre>

<hr>

<h2>22. Name Locator in Registration Form</h2>

<pre><code>&lt;input type="text" name="firstName"&gt;

&lt;input type="text" name="lastName"&gt;

&lt;input type="email" name="email"&gt;

&lt;input type="password" name="password"&gt;

&lt;input type="password" name="confirmPassword"&gt;

&lt;button type="submit" name="register"&gt;Register&lt;/button&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("lastName")).sendKeys("Smith");

driver.findElement(By.name("email")).sendKeys("[email protected]");

driver.findElement(By.name("password")).sendKeys("Pass@123");

driver.findElement(By.name("confirmPassword")).sendKeys("Pass@123");

driver.findElement(By.name("register")).click();</code></pre>

<hr>

<h2>23. Name Locator in Search Form</h2>

<pre><code>&lt;input type="text" name="query"&gt;

&lt;button type="submit" name="search"&gt;Search&lt;/button&gt;</code></pre>

<pre><code>driver.findElement(By.name("query")).sendKeys("Laptop");

driver.findElement(By.name("search")).click();</code></pre>

<hr>

<h2>24. Name Locator for Checkboxes</h2>

<p>Checkboxes can use the same <code>name</code> when they represent a group of related options.</p>

<pre><code>&lt;input type="checkbox" name="skills" value="java"&gt;

&lt;input type="checkbox" name="skills" value="selenium"&gt;

&lt;input type="checkbox" name="skills" value="sql"&gt;</code></pre>

<p>To locate all matching checkboxes:</p>

<pre><code>List&lt;WebElement&gt; skills = driver.findElements(By.name("skills"));

 

System.out.println("Number of skills: " + skills.size());</code></pre>

<hr>

<h2>25. Name Locator for Radio Button Groups</h2>

<p>Radio buttons commonly share the same <code>name</code> value because the name groups them together.</p>

<pre><code>&lt;input type="radio" name="payment" value="card"&gt;

&lt;input type="radio" name="payment" value="upi"&gt;

&lt;input type="radio" name="payment" value="cash"&gt;</code></pre>

<p>All radio buttons can be located using:</p>

<pre><code>List&lt;WebElement&gt; paymentOptions = driver.findElements(By.name("payment"));</code></pre>

<hr>

<h2>26. Selecting a Radio Button by Name and Value</h2>

<p>Because multiple radio buttons can share the same name, the <code>name</code> locator alone may return multiple elements.</p>

<pre><code>List&lt;WebElement&gt; options = driver.findElements(By.name("payment"));

 

for (WebElement option : options) {

    if ("upi".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>27. Name Locator with findElement()</h2>

<p><code>findElement()</code> returns one matching WebElement.</p>

<pre><code>WebElement username = driver.findElement(By.name("username"));</code></pre>

<p>If no matching element exists, Selenium can throw <code>NoSuchElementException</code>.</p>

<hr>

<h2>28. Name Locator with findElements()</h2>

<p><code>findElements()</code> returns a list of matching WebElements.</p>

<pre><code>List&lt;WebElement&gt; elements = driver.findElements(By.name("username"));</code></pre>

<p>If no matching elements are found, <code>findElements()</code> returns an empty list.</p>

<hr>

<h2>29. Difference Between findElement() and findElements()</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>findElement()</th><th>findElements()</th></tr>

<tr><td>Return Type</td><td>WebElement</td><td>List&lt;WebElement&gt;</td></tr>

<tr><td>Multiple Matches</td><td>Returns first matching element</td><td>Returns all matching elements</td></tr>

<tr><td>No Match</td><td>Throws NoSuchElementException</td><td>Returns empty list</td></tr>

<tr><td>Typical Use</td><td>Single field</td><td>Groups of elements</td></tr>

</table>

<hr>

<h2>30. Name Locator with Multiple Elements</h2>

<p>Suppose a page contains:</p>

<pre><code>&lt;input type="text" name="username"&gt;

&lt;input type="text" name="username"&gt;

&lt;input type="text" name="username"&gt;</code></pre>

<p>Using:</p>

<pre><code>driver.findElement(By.name("username"));</code></pre>

<p>will locate the first matching element.</p>

<p>Using:</p>

<pre><code>driver.findElements(By.name("username"));</code></pre>

<p>will return all matching elements.</p>

<hr>

<h2>31. Checking the Number of Elements</h2>

<pre><code>List&lt;WebElement&gt; fields = driver.findElements(By.name("username"));

 

System.out.println("Count: " + fields.size());</code></pre>

<p>This can be useful when testing repeated fields or grouped controls.</p>

<hr>

<h2>32. Name Locator and Unique Values</h2>

<p>A Name Locator works particularly well when the target element has a meaningful and stable <code>name</code> attribute.</p>

<pre><code>&lt;input type="email" name="emailAddress"&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("emailAddress")).sendKeys("[email protected]");</code></pre>

<hr>

<h2>33. Name Attribute Does Not Always Mean Unique Element</h2>

<p>Unlike an ID, the same <code>name</code> value can legitimately appear on multiple elements. This is especially common with radio buttons and groups of checkboxes.</p>

<pre><code>&lt;input type="radio" name="gender" value="male"&gt;

&lt;input type="radio" name="gender" value="female"&gt;</code></pre>

<p>Both elements have the same name.</p>

<hr>

<h2>34. Name Locator vs ID Locator</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>ID Locator</th><th>Name Locator</th></tr>

<tr><td>Java Syntax</td><td>By.id("value")</td><td>By.name("value")</td></tr>

<tr><td>HTML Attribute</td><td>id</td><td>name</td></tr>

<tr><td>Typical Use</td><td>Unique elements</td><td>Form elements and grouped controls</td></tr>

<tr><td>Can Be Shared</td><td>IDs are intended to be unique</td><td>Name values can be shared</td></tr>

<tr><td>Multiple Matches</td><td>Usually unexpected</td><td>Common in groups</td></tr>

</table>

<hr>

<h2>35. Name Locator vs Class Name Locator</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Name</th><th>Class Name</th></tr>

<tr><td>Attribute</td><td>name</td><td>class</td></tr>

<tr><td>Selenium Method</td><td>By.name()</td><td>By.className()</td></tr>

<tr><td>Common Use</td><td>Form controls</td><td>Styling/grouping</td></tr>

<tr><td>Example</td><td>name="email"</td><td>class="input-field"</td></tr>

</table>

<hr>

<h2>36. Name Locator vs Tag Name</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Name Locator</th><th>Tag Name</th></tr>

<tr><td>Method</td><td>By.name()</td><td>By.tagName()</td></tr>

<tr><td>Uses</td><td>name attribute</td><td>HTML tag</td></tr>

<tr><td>Example</td><td>name="username"</td><td>input</td></tr>

</table>

<hr>

<h2>37. Name Locator vs XPath</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Name Locator</th><th>XPath</th></tr>

<tr><td>Syntax</td><td>By.name("username")</td><td>By.xpath("//input[@name='username']")</td></tr>

<tr><td>Complexity</td><td>Simple</td><td>Can be simple or complex</td></tr>

<tr><td>Text Matching</td><td>No direct support</td><td>Supported</td></tr>

<tr><td>Relationships</td><td>No</td><td>Yes</td></tr>

<tr><td>Best Use</td><td>Stable name attribute</td><td>Complex element identification</td></tr>

</table>

<hr>

<h2>38. Name Locator vs CSS Selector</h2>

<p>A CSS attribute selector can locate an element using its <code>name</code> attribute.</p>

<pre><code>driver.findElement(By.cssSelector("[name='username']"));</code></pre>

<p>The direct Name Locator is:</p>

<pre><code>driver.findElement(By.name("username"));</code></pre>

<hr>

<h2>39. Name Locator with CSS Attribute Selector</h2>

<p>CSS selectors can also be used when additional attributes need to be included.</p>

<pre><code>driver.findElement(

    By.cssSelector("input[name='username']")

);</code></pre>

<p>This identifies an <code>input</code> element whose <code>name</code> attribute is <code>username</code>.</p>

<hr>

<h2>40. Name Locator with XPath</h2>

<p>The equivalent XPath can be:</p>

<pre><code>driver.findElement(By.xpath("//input[@name='username']"));</code></pre>

<p>When only a stable name is required, <code>By.name()</code> provides a simpler syntax.</p>

<hr>

<h2>41. Dynamic Name Attributes</h2>

<p>Some applications generate dynamic values for the <code>name</code> attribute.</p>

<pre><code>&lt;input name="user_12345" type="text"&gt;</code></pre>

<p>On another execution, it might become:</p>

<pre><code>&lt;input name="user_98765" type="text"&gt;</code></pre>

<p>A locator using the complete changing value may become unreliable.</p>

<hr>

<h2>42. Handling Dynamic Name Attributes</h2>

<p>When the name changes dynamically, inspect the element for another stable attribute.</p>

<pre><code>&lt;input name="user_12345" id="username" type="text"&gt;</code></pre>

<p>If the ID is stable, use:</p>

<pre><code>driver.findElement(By.id("username"));</code></pre>

<p>Other alternatives can include CSS selectors or XPath depending on the HTML structure.</p>

<hr>

<h2>43. Name Locator with Explicit Wait</h2>

<p>When a name-based element is loaded dynamically, an explicit wait can be used.</p>

<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement username = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.name("username")

    )

);

 

username.sendKeys("admin");</code></pre>

<hr>

<h2>44. Name Locator with ElementToBeClickable</h2>

<p>For a button identified by name:</p>

<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement login = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.name("login")

    )

);

 

login.click();</code></pre>

<hr>

<h2>45. Required Wait Imports</h2>

<pre><code>import java.time.Duration;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;</code></pre>

<hr>

<h2>46. Name Locator and Iframes</h2>

<p>If an element is inside an iframe, Selenium must switch to the correct iframe before using the Name Locator.</p>

<pre><code>WebElement frame = driver.findElement(By.id("loginFrame"));

driver.switchTo().frame(frame);

 

driver.findElement(By.name("username")).sendKeys("admin");

 

driver.switchTo().defaultContent();</code></pre>

<hr>

<h2>47. Name Locator and Windows or Tabs</h2>

<p>If the required element is present in another browser window or tab, switch to that window before locating the element.</p>

<pre><code>String originalWindow = driver.getWindowHandle();

 

for (String window : driver.getWindowHandles()) {

    if (!window.equals(originalWindow)) {

        driver.switchTo().window(window);

        break;

    }

}

 

driver.findElement(By.name("username")).sendKeys("admin");</code></pre>

<hr>

<h2>48. Name Locator and Shadow DOM</h2>

<p>Elements inside a Shadow DOM may require Shadow Root handling. Simply using <code>By.name()</code> from the document context may not locate an element inside a shadow tree.</p>

<p>The correct strategy depends on the application's Shadow DOM implementation and the WebDriver APIs being used.</p>

<hr>

<h2>49. Name Locator and Dynamic Web Applications</h2>

<p>Modern web applications can create or update elements dynamically. An element may have a valid <code>name</code> but may not be present when Selenium first searches for it.</p>

<p>In such situations, synchronization should be considered:</p>

<pre><code>WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement email = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.name("email")

    )

);

 

email.sendKeys("[email protected]");</code></pre>

<hr>

<h2>50. Name Locator with AJAX Content</h2>

<p>If an AJAX request adds a form field after the page loads, Selenium may need to wait for the field.</p>

<pre><code>WebElement search = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.visibilityOfElementLocated(

        By.name("search")

    )

);

 

search.sendKeys("Selenium");</code></pre>

<hr>

<h2>51. Name Locator for Multiple Checkboxes</h2>

<pre><code>&lt;input type="checkbox" name="hobby" value="reading"&gt;

&lt;input type="checkbox" name="hobby" value="coding"&gt;

&lt;input type="checkbox" name="hobby" value="travel"&gt;</code></pre>

<p>Locate all checkboxes:</p>

<pre><code>List&lt;WebElement&gt; hobbies = driver.findElements(By.name("hobby"));</code></pre>

<hr>

<h2>52. Selecting a Specific Checkbox by Value</h2>

<pre><code>List&lt;WebElement&gt; hobbies = driver.findElements(By.name("hobby"));

 

for (WebElement hobby : hobbies) {

    if ("coding".equals(hobby.getAttribute("value"))) {

        if (!hobby.isSelected()) {

            hobby.click();

        }

        break;

    }

}</code></pre>

<hr>

<h2>53. Selecting a Specific Radio Button by Value</h2>

<pre><code>List&lt;WebElement&gt; paymentOptions = driver.findElements(By.name("payment"));

 

for (WebElement option : paymentOptions) {

    if ("card".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>54. Name Locator for Select Elements</h2>

<p>A standard HTML select element can have a name attribute.</p>

<pre><code>&lt;select name="country"&gt;

    &lt;option value="india"&gt;India&lt;/option&gt;

    &lt;option value="usa"&gt;USA&lt;/option&gt;

&lt;/select&gt;</code></pre>

<p>The select element can be located using:</p>

<pre><code>WebElement country = driver.findElement(By.name("country"));</code></pre>

<p>The Selenium <code>Select</code> class can then be used to select an option.</p>

<pre><code>Select select = new Select(country);

select.selectByValue("india");</code></pre>

<hr>

<h2>55. Name Locator for Dropdowns</h2>

<p>Complete example:</p>

<pre><code>WebElement countryElement = driver.findElement(By.name("country"));

 

Select country = new Select(countryElement);

country.selectByVisibleText("India");</code></pre>

<hr>

<h2>56. Import for Select Class</h2>

<pre><code>import org.openqa.selenium.support.ui.Select;</code></pre>

<hr>

<h2>57. Name Locator for Textarea</h2>

<p>A textarea can also have a name attribute.</p>

<pre><code>&lt;textarea name="address"&gt;&lt;/textarea&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("address"))

      .sendKeys("Mumbai, Maharashtra");</code></pre>

<hr>

<h2>58. Name Locator for File Upload</h2>

<pre><code>&lt;input type="file" name="resume"&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("resume"))

      .sendKeys("C:\\files\\resume.pdf");</code></pre>

<p>For file upload controls, <code>sendKeys()</code> can be used to provide the file path when the control supports direct file selection.</p>

<hr>

<h2>59. Name Locator for Hidden Inputs</h2>

<pre><code>&lt;input type="hidden" name="token" value="ABC123"&gt;</code></pre>

<p>Selenium may locate the element:</p>

<pre><code>WebElement token = driver.findElement(By.name("token"));

System.out.println(token.getAttribute("value"));</code></pre>

<p>However, hidden elements are generally not directly interactable like visible form controls.</p>

<hr>

<h2>60. Name Locator for Error Messages</h2>

<pre><code>&lt;span name="emailError"&gt;Invalid email&lt;/span&gt;</code></pre>

<p>Selenium:</p>

<pre><code>String error = driver.findElement(By.name("emailError")).getText();

System.out.println(error);</code></pre>

<hr>

<h2>61. Name Locator for Success Messages</h2>

<pre><code>&lt;div name="successMessage"&gt;Registration successful&lt;/div&gt;</code></pre>

<p>Selenium:</p>

<pre><code>String message = driver.findElement(By.name("successMessage")).getText();

System.out.println(message);</code></pre>

<hr>

<h2>62. Name Locator and isDisplayed()</h2>

<pre><code>WebElement message = driver.findElement(By.name("successMessage"));

 

if (message.isDisplayed()) {

    System.out.println("Message is displayed.");

}</code></pre>

<hr>

<h2>63. Name Locator and isEnabled()</h2>

<pre><code>WebElement submit = driver.findElement(By.name("submit"));

 

if (submit.isEnabled()) {

    System.out.println("Submit button is enabled.");

}</code></pre>

<hr>

<h2>64. Name Locator and isSelected()</h2>

<p>This method is particularly useful for checkboxes and radio buttons.</p>

<pre><code>WebElement option = driver.findElement(By.name("gender"));

 

System.out.println(option.isSelected());</code></pre>

<p>When multiple radio buttons share the same name, use <code>findElements()</code> and inspect each element.</p>

<hr>

<h2>65. Complete State Validation</h2>

<pre><code>WebElement checkbox = driver.findElement(By.name("terms"));

 

System.out.println("Displayed: " + checkbox.isDisplayed());

System.out.println("Enabled: " + checkbox.isEnabled());

System.out.println("Selected: " + checkbox.isSelected());</code></pre>

<hr>

<h2>66. Name Locator and Forms</h2>

<p>Name locators are especially useful in form automation because many form controls naturally contain name attributes.</p>

<pre><code>&lt;form&gt;

    &lt;input name="firstName"&gt;

    &lt;input name="lastName"&gt;

    &lt;input name="email"&gt;

    &lt;textarea name="address"&gt;&lt;/textarea&gt;

    &lt;button name="submit"&gt;Submit&lt;/button&gt;

&lt;/form&gt;</code></pre>

<hr>

<h2>67. Complete Form Automation with Name Locators</h2>

<pre><code>driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("lastName")).sendKeys("Smith");

driver.findElement(By.name("email")).sendKeys("[email protected]");

driver.findElement(By.name("address")).sendKeys("Mumbai, Maharashtra");

driver.findElement(By.name("submit")).click();</code></pre>

<hr>

<h2>68. Name Locator in Page Object Model</h2>

<p>In the Page Object Model, Name Locators can be stored as private fields.</p>

<pre><code>public class LoginPage {

 

    private WebDriver driver;

 

    private By username = By.name("username");

    private By password = By.name("password");

    private By loginButton = By.name("login");

 

    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(loginButton).click();

    }

}</code></pre>

<hr>

<h2>69. Benefits of Name Locators in POM</h2>

<ul>

<li>Locators are centralized.</li>

<li>Page classes become easier to maintain.</li>

<li>Test methods become cleaner.</li>

<li>Form fields are easy to identify.</li>

<li>Repeated locator definitions can be avoided.</li>

<li>Locator changes can be made in one place.</li>

</ul>

<hr>

<h2>70. Name Locator with TestNG</h2>

<pre><code>import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;

 

public class LoginTest {

 

    @Test

    public void loginTest() {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        driver.findElement(By.name("username")).sendKeys("admin");

        driver.findElement(By.name("password")).sendKeys("admin123");

        driver.findElement(By.name("login")).click();

 

        driver.quit();

    }

}</code></pre>

<hr>

<h2>71. Name Locator with TestNG Assertion</h2>

<pre><code>import org.testng.Assert;

 

WebElement message = driver.findElement(By.name("successMessage"));

 

Assert.assertTrue(message.isDisplayed());</code></pre>

<hr>

<h2>72. Name Locator with Text Validation</h2>

<pre><code>String actualMessage =

    driver.findElement(By.name("successMessage")).getText();

 

Assert.assertEquals(actualMessage, "Registration successful");</code></pre>

<hr>

<h2>73. Name Locator with Reusable Utility</h2>

<pre><code>public void enterText(By locator, String text) {

    WebElement element = driver.findElement(locator);

    element.clear();

    element.sendKeys(text);

}</code></pre>

<p>Usage:</p>

<pre><code>enterText(By.name("username"), "admin");

enterText(By.name("email"), "[email protected]");</code></pre>

<hr>

<h2>74. Reusable Click Utility</h2>

<pre><code>public void click(By locator) {

    driver.findElement(locator).click();

}</code></pre>

<p>Usage:</p>

<pre><code>click(By.name("login"));

click(By.name("submit"));</code></pre>

<hr>

<h2>75. Explicit Wait Utility for Name Locator</h2>

<pre><code>public WebElement waitForElement(By locator) {

 

    WebDriverWait wait =

        new WebDriverWait(driver, Duration.ofSeconds(10));

 

    return wait.until(

        ExpectedConditions.visibilityOfElementLocated(locator)

    );

}</code></pre>

<p>Usage:</p>

<pre><code>WebElement username = waitForElement(By.name("username"));

username.sendKeys("admin");</code></pre>

<hr>

<h2>76. Common Exceptions with Name Locator</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Exception</th><th>Possible Cause</th></tr>

<tr><td>NoSuchElementException</td><td>Incorrect name or element not available</td></tr>

<tr><td>ElementNotInteractableException</td><td>Element exists but cannot be interacted with</td></tr>

<tr><td>ElementClickInterceptedException</td><td>Another element blocks the interaction</td></tr>

<tr><td>StaleElementReferenceException</td><td>DOM changed after locating the element</td></tr>

<tr><td>TimeoutException</td><td>Wait condition was not satisfied</td></tr>

</table>

<hr>

<h2>77. NoSuchElementException with Name</h2>

<p>Example:</p>

<pre><code>driver.findElement(By.name("wrongName")).click();</code></pre>

<p>If no element contains <code>name="wrongName"</code> in the current browsing context, Selenium can throw <code>NoSuchElementException</code>.</p>

<p>Check:</p>

<ul>

<li>The spelling of the name.</li>

<li>Uppercase and lowercase characters.</li>

<li>The current page.</li>

<li>Whether the element has loaded.</li>

<li>Whether the element is inside an iframe.</li>

<li>Whether the name is dynamically generated.</li>

</ul>

<hr>

<h2>78. ElementNotInteractableException</h2>

<p>An element may exist in the DOM but not be ready for interaction.</p>

<pre><code>driver.findElement(By.name("username")).sendKeys("admin");</code></pre>

<p>If the field is hidden, disabled, or otherwise not interactable, synchronization or another interaction strategy may be required.</p>

<hr>

<h2>79. ElementClickInterceptedException</h2>

<p>This exception can occur when another element overlays the target.</p>

<pre><code>driver.findElement(By.name("submit")).click();</code></pre>

<p>Possible causes include:</p>

<ul>

<li>Popup overlay.</li>

<li>Modal dialog.</li>

<li>Loading layer.</li>

<li>Sticky header.</li>

<li>Animation.</li>

</ul>

<p>An appropriate explicit wait and correct application state should generally be used before attempting the interaction.</p>

<hr>

<h2>80. StaleElementReferenceException</h2>

<p>A WebElement reference can become stale if the page or DOM is refreshed or rebuilt.</p>

<pre><code>WebElement username = driver.findElement(By.name("username"));

 

driver.navigate().refresh();

 

username.sendKeys("admin");</code></pre>

<p>After the refresh, the old reference may no longer represent the current DOM element. Locate the element again when necessary.</p>

<hr>

<h2>81. Name Locator Best Practices</h2>

<ul>

<li>Use a stable name attribute whenever available.</li>

<li>Verify the name value in browser developer tools.</li>

<li>Do not assume the name value is unique.</li>

<li>Use <code>findElements()</code> for groups that intentionally share the same name.</li>

<li>Combine name with value or another stable attribute when necessary.</li>

<li>Use explicit waits for dynamically loaded elements.</li>

<li>Store important locators in Page Object classes.</li>

<li>Avoid hard-coding frequently changing dynamic names.</li>

<li>Keep locator names readable.</li>

<li>Validate the result after performing an action.</li>

</ul>

<hr>

<h2>82. Common Mistakes with Name Locator</h2>

<h3>Mistake 1: Using the Wrong Attribute</h3>

<p>Do not confuse <code>name</code> with <code>id</code>.</p>

<pre><code>&lt;input id="username" name="user"&gt;</code></pre>

<p>The correct Name Locator is:</p>

<pre><code>By.name("user")</code></pre>

<p>The correct ID Locator is:</p>

<pre><code>By.id("username")</code></pre>

<h3>Mistake 2: Assuming Name Is Unique</h3>

<p>Multiple elements can have the same name, especially radio buttons and checkboxes.</p>

<h3>Mistake 3: Ignoring Dynamic Names</h3>

<p>A generated name can change between executions.</p>

<h3>Mistake 4: Ignoring Iframes</h3>

<p>Elements inside an iframe require switching to the correct frame.</p>

<h3>Mistake 5: Not Waiting for Dynamic Content</h3>

<p>AJAX and JavaScript-based applications may add the element after the initial page load.</p>

<hr>

<h2>83. Name Locator for Dynamic Forms</h2>

<p>Dynamic forms can add fields based on user selections.</p>

<pre><code>driver.findElement(By.name("accountType")).click();

 

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement companyName = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.name("companyName")

    )

);

 

companyName.sendKeys("ABC Technologies");</code></pre>

<hr>

<h2>84. Name Locator for Payment Options</h2>

<pre><code>&lt;input type="radio" name="payment" value="card"&gt;

&lt;input type="radio" name="payment" value="upi"&gt;

&lt;input type="radio" name="payment" value="netbanking"&gt;</code></pre>

<p>Selenium:</p>

<pre><code>List&lt;WebElement&gt; paymentOptions =

    driver.findElements(By.name("payment"));

 

for (WebElement option : paymentOptions) {

    if ("upi".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>85. Name Locator for Delivery Options</h2>

<pre><code>&lt;input type="radio" name="delivery" value="standard"&gt;

&lt;input type="radio" name="delivery" value="express"&gt;</code></pre>

<p>Selenium:</p>

<pre><code>List&lt;WebElement&gt; deliveryOptions =

    driver.findElements(By.name("delivery"));

 

for (WebElement option : deliveryOptions) {

    if ("express".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>86. Name Locator for Subscription Options</h2>

<pre><code>&lt;input type="radio" name="subscription" value="free"&gt;

&lt;input type="radio" name="subscription" value="premium"&gt;</code></pre>

<pre><code>List&lt;WebElement&gt; plans =

    driver.findElements(By.name("subscription"));

 

for (WebElement plan : plans) {

    if ("premium".equals(plan.getAttribute("value"))) {

        plan.click();

        break;

    }

}</code></pre>

<hr>

<h2>87. Name Locator for Yes/No Options</h2>

<pre><code>&lt;input type="radio" name="newsletter" value="yes"&gt;

&lt;input type="radio" name="newsletter" value="no"&gt;</code></pre>

<pre><code>List&lt;WebElement&gt; options =

    driver.findElements(By.name("newsletter"));

 

for (WebElement option : options) {

    if ("yes".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>88. Name Locator with Label and Input</h2>

<p>Sometimes the label and input use different attributes.</p>

<pre><code>&lt;label for="username"&gt;Username&lt;/label&gt;

&lt;input id="username" name="username"&gt;</code></pre>

<p>The input can be located directly using:</p>

<pre><code>driver.findElement(By.name("username")).sendKeys("admin");</code></pre>

<hr>

<h2>89. Name Locator in Tables</h2>

<p>Name attributes may occasionally be used for action controls inside tables.</p>

<pre><code>&lt;button name="editUser"&gt;Edit&lt;/button&gt;

&lt;button name="deleteUser"&gt;Delete&lt;/button&gt;</code></pre>

<p>Selenium:</p>

<pre><code>driver.findElement(By.name("editUser")).click();</code></pre>

<p>If the same name is used in multiple rows, use <code>findElements()</code> or combine the locator with row-specific information.</p>

<hr>

<h2>90. Name Locator for Multiple Products</h2>

<pre><code>&lt;button name="addToCart" value="laptop"&gt;Add&lt;/button&gt;

&lt;button name="addToCart" value="phone"&gt;Add&lt;/button&gt;

&lt;button name="addToCart" value="tablet"&gt;Add&lt;/button&gt;</code></pre>

<p>To select the phone:</p>

<pre><code>List&lt;WebElement&gt; buttons =

    driver.findElements(By.name("addToCart"));

 

for (WebElement button : buttons) {

    if ("phone".equals(button.getAttribute("value"))) {

        button.click();

        break;

    }

}</code></pre>

<hr>

<h2>91. Name Locator in Real-World E-Commerce</h2>

<p>In an e-commerce application, Name Locators can be used for search fields, checkout forms, address fields, payment options, and form controls when the application provides stable name attributes.</p>

<pre><code>driver.findElement(By.name("search")).sendKeys("Laptop");

driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("address")).sendKeys("Mumbai");

driver.findElement(By.name("checkout")).click();</code></pre>

<hr>

<h2>92. Name Locator in Real-World Registration</h2>

<pre><code>driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("lastName")).sendKeys("Smith");

driver.findElement(By.name("email")).sendKeys("[email protected]");

driver.findElement(By.name("password")).sendKeys("Pass@123");

 

WebElement terms = driver.findElement(By.name("terms"));

 

if (!terms.isSelected()) {

    terms.click();

}

 

driver.findElement(By.name("register")).click();</code></pre>

<hr>

<h2>93. Name Locator in Real-World Login</h2>

<pre><code>driver.get("https://example.com/login");

 

driver.findElement(By.name("username")).sendKeys("admin");

driver.findElement(By.name("password")).sendKeys("admin123");

driver.findElement(By.name("login")).click();</code></pre>

<hr>

<h2>94. Name Locator in Test Automation Framework</h2>

<p>A framework can organize Name Locators in separate page classes.</p>

<pre><code>public class RegistrationPage {

 

    private WebDriver driver;

 

    private By firstName = By.name("firstName");

    private By lastName = By.name("lastName");

    private By email = By.name("email");

    private By password = By.name("password");

    private By register = By.name("register");

 

    public RegistrationPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void registerUser(

        String first,

        String last,

        String emailValue,

        String passwordValue

    ) {

        driver.findElement(firstName).sendKeys(first);

        driver.findElement(lastName).sendKeys(last);

        driver.findElement(email).sendKeys(emailValue);

        driver.findElement(password).sendKeys(passwordValue);

        driver.findElement(register).click();

    }

}</code></pre>

<hr>

<h2>95. Name Locator and Maintainability</h2>

<p>Stable Name Locators can make automation code easier to maintain, particularly when the name attributes are meaningful and remain consistent across application releases.</p>

<p>For example:</p>

<pre><code>By.name("username")</code></pre>

<p>is straightforward to understand and can clearly communicate which field the test is accessing.</p>

<hr>

<h2>96. Name Locator and Readability</h2>

<p>Readable automation code helps testers understand the purpose of a test quickly.</p>

<pre><code>driver.findElement(By.name("email")).sendKeys("[email protected]");</code></pre>

<p>The statement clearly indicates that an email field is being populated.</p>

<hr>

<h2>97. Name Locator and Test Stability</h2>

<p>Test stability depends on the consistency of the application's HTML. A stable name attribute can provide a useful locator, while a frequently changing name can cause failures.</p>

<p>Before selecting a Name Locator, inspect whether the value is stable across page loads and application releases.</p>

<hr>

<h2>98. Name Locator Decision Flow</h2>

<pre><code>Start

  |

  v

Inspect Web Element

  |

  v

Does it have a name attribute?

  |

  +---- No ----&gt; Consider ID / Class / CSS / XPath

  |

 Yes

  |

  v

Is the name stable?

  |

  +---- No ----&gt; Find another stable locator

  |

 Yes

  |

  v

Is the name unique?

  |

  +---- Yes ----&gt; Use By.name("value")

  |

  +---- No ----&gt; Use findElements()

                    |

                    v

             Identify specific

             element by value

             or another attribute</code></pre>

<hr>

<h2>99. Name Locator Validation Checklist</h2>

<ul>

<li>Inspect the HTML element.</li>

<li>Find the <code>name</code> attribute.</li>

<li>Copy the exact name value.</li>

<li>Check spelling and case.</li>

<li>Determine whether the name is unique.</li>

<li>Check whether the name is stable.</li>

<li>Use <code>By.name()</code> when appropriate.</li>

<li>Use <code>findElements()</code> for grouped controls.</li>

<li>Use value or another stable attribute to distinguish multiple elements.</li>

<li>Add explicit waits when elements load dynamically.</li>

<li>Switch into the correct iframe when required.</li>

<li>Validate the expected result after the interaction.</li>

</ul>

<hr>

<h2>100. Name Locator Quick Reference</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Action</th><th>Example</th></tr>

<tr><td>Locate</td><td>driver.findElement(By.name("username"))</td></tr>

<tr><td>Type</td><td>driver.findElement(By.name("username")).sendKeys("admin")</td></tr>

<tr><td>Clear</td><td>driver.findElement(By.name("username")).clear()</td></tr>

<tr><td>Click</td><td>driver.findElement(By.name("login")).click()</td></tr>

<tr><td>Get Text</td><td>driver.findElement(By.name("message")).getText()</td></tr>

<tr><td>Get Attribute</td><td>driver.findElement(By.name("email")).getAttribute("value")</td></tr>

<tr><td>Displayed</td><td>driver.findElement(By.name("message")).isDisplayed()</td></tr>

<tr><td>Enabled</td><td>driver.findElement(By.name("submit")).isEnabled()</td></tr>

<tr><td>Selected</td><td>driver.findElement(By.name("terms")).isSelected()</td></tr>

<tr><td>Multiple Elements</td><td>driver.findElements(By.name("payment"))</td></tr>

</table>

<hr>

<h2>101. Name Locator Best-Practice Summary</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Practice</th><th>Recommendation</th></tr>

<tr><td>Stable Name</td><td>Prefer a name value that remains consistent.</td></tr>

<tr><td>Unique Name</td><td>Use findElement() when one matching element is expected.</td></tr>

<tr><td>Shared Name</td><td>Use findElements() for groups such as radio buttons.</td></tr>

<tr><td>Dynamic Name</td><td>Consider another stable locator strategy.</td></tr>

<tr><td>Specific Element</td><td>Use another attribute such as value when multiple elements share the name.</td></tr>

<tr><td>Synchronization</td><td>Use explicit waits for dynamically loaded elements.</td></tr>

<tr><td>POM</td><td>Keep important locators inside Page Object classes.</td></tr>

<tr><td>Validation</td><td>Verify the expected result after performing actions.</td></tr>

</table>

<hr>

<h2>102. Interview Question: What is a Name Locator?</h2>

<p><strong>Answer:</strong> A Name Locator is a Selenium WebDriver locator strategy that identifies a web element using the value of its HTML <code>name</code> attribute. In Java Selenium, it is written using <code>By.name("value")</code>.</p>

<hr>

<h2>103. Interview Question: What is the Syntax of Name Locator?</h2>

<p><strong>Answer:</strong></p>

<pre><code>driver.findElement(By.name("username"));</code></pre>

<p>For entering data:</p>

<pre><code>driver.findElement(By.name("username")).sendKeys("admin");</code></pre>

<hr>

<h2>104. Interview Question: Where is Name Locator Commonly Used?</h2>

<p><strong>Answer:</strong> Name Locators are commonly used for form fields such as username, password, email, search boxes, textareas, checkboxes, radio buttons, and other controls that contain a suitable <code>name</code> attribute.</p>

<hr>

<h2>105. Interview Question: Is Name Attribute Always Unique?</h2>

<p><strong>Answer:</strong> No. Multiple elements can share the same <code>name</code> value. Radio buttons often share a name to represent one group, and checkboxes may also use the same name for related options.</p>

<hr>

<h2>106. Interview Question: What If Multiple Elements Have the Same Name?</h2>

<p><strong>Answer:</strong> Use <code>findElements(By.name("value"))</code> to retrieve all matching elements, then inspect another attribute such as <code>value</code> to identify the required element.</p>

<hr>

<h2>107. Interview Question: Name Locator vs ID Locator?</h2>

<p><strong>Answer:</strong> ID Locator uses the HTML <code>id</code> attribute, while Name Locator uses the <code>name</code> attribute. IDs are intended to uniquely identify elements, whereas name values can be shared by multiple controls.</p>

<hr>

<h2>108. Interview Question: Name Locator vs XPath?</h2>

<p><strong>Answer:</strong> Name Locator provides a simple direct way to locate an element using its name attribute. XPath can handle more complex conditions, text matching, and relationships between elements.</p>

<hr>

<h2>109. Interview Question: Can Name Locator Be Used for Radio Buttons?</h2>

<p><strong>Answer:</strong> Yes. Radio buttons commonly share the same name. In such cases, use <code>findElements()</code> and identify the desired option using another attribute such as <code>value</code>.</p>

<hr>

<h2>110. Interview Question: Can Name Locator Be Used for Checkboxes?</h2>

<p><strong>Answer:</strong> Yes. If checkboxes have a common name, they can be located using <code>findElements(By.name())</code> and individual options can be identified using attributes such as <code>value</code>.</p>

<hr>

<h2>111. Interview Question: What Happens If the Name Is Incorrect?</h2>

<p><strong>Answer:</strong> If no matching element exists in the current browsing context, <code>findElement()</code> can throw <code>NoSuchElementException</code>.</p>

<hr>

<h2>112. Interview Question: How Do You Handle Dynamic Name Values?</h2>

<p><strong>Answer:</strong> Inspect the HTML for a more stable attribute or relationship. Depending on the application, ID, CSS Selector, XPath, or another reliable locator may be appropriate.</p>

<hr>

<h2>113. Interview Question: Can Name Locator Be Used with Explicit Wait?</h2>

<p><strong>Answer:</strong> Yes. Any Selenium locator can be passed to explicit wait conditions.</p>

<pre><code>WebElement username = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

).until(

    ExpectedConditions.visibilityOfElementLocated(

        By.name("username")

    )

);</code></pre>

<hr>

<h2>114. Practical Project: Login Automation Using Name Locator</h2>

<p>Automate a login page using Name Locators for username, password, and login button.</p>

<pre><code>driver.get("https://example.com/login");

 

driver.findElement(By.name("username")).sendKeys("admin");

driver.findElement(By.name("password")).sendKeys("admin123");

driver.findElement(By.name("login")).click();

 

WebElement message = driver.findElement(By.name("successMessage"));

 

System.out.println(message.getText());</code></pre>

<hr>

<h2>115. Practical Project: Registration Automation Using Name Locator</h2>

<pre><code>driver.findElement(By.name("firstName")).sendKeys("John");

driver.findElement(By.name("lastName")).sendKeys("Smith");

driver.findElement(By.name("email")).sendKeys("[email protected]");

driver.findElement(By.name("password")).sendKeys("Pass@123");

driver.findElement(By.name("confirmPassword")).sendKeys("Pass@123");

 

WebElement terms = driver.findElement(By.name("terms"));

 

if (!terms.isSelected()) {

    terms.click();

}

 

driver.findElement(By.name("register")).click();</code></pre>

<hr>

<h2>116. Practical Project: Payment Selection</h2>

<pre><code>List&lt;WebElement&gt; paymentOptions =

    driver.findElements(By.name("payment"));

 

for (WebElement option : paymentOptions) {

 

    if ("card".equals(option.getAttribute("value"))) {

        option.click();

        break;

    }

}</code></pre>

<hr>

<h2>117. Practical Project: Multiple Checkbox Selection</h2>

<pre><code>List&lt;WebElement&gt; skills =

    driver.findElements(By.name("skills"));

 

for (WebElement skill : skills) {

 

    String value = skill.getAttribute("value");

 

    if ("java".equals(value) || "selenium".equals(value)) {

 

        if (!skill.isSelected()) {

            skill.click();

        }

    }

}</code></pre>

<hr>

<h2>118. Complete Name Locator Example</h2>

<pre><code>import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class CompleteNameLocatorExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.manage().window().maximize();

            driver.get("https://example.com/login");

 

            WebDriverWait wait =

                new WebDriverWait(driver, Duration.ofSeconds(10));

 

            WebElement username = wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.name("username")

                )

            );

 

            WebElement password =

                driver.findElement(By.name("password"));

 

            WebElement loginButton =

                driver.findElement(By.name("login"));

 

            username.sendKeys("admin");

            password.sendKeys("admin123");

            loginButton.click();

 

            WebElement message = wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                    By.name("successMessage")

                )

            );

 

            System.out.println(message.getText());

 

        } finally {

            driver.quit();

        }

    }

}</code></pre>

<hr>

<h2>119. Name Locator Automation Workflow</h2>

<pre><code>Open Web Page

      |

      v

Inspect HTML

      |

      v

Find name Attribute

      |

      v

Check Name Stability

      |

      v

Is Name Unique?

      |

      +---- Yes ----&gt; Use By.name()

      |

      +---- No -----&gt; Use findElements()

                          |

                          v

                    Check value or

                    another attribute

                          |

                          v

                    Locate Target

                          |

                          v

                    Perform Action

                          |

                          v

                    Validate Result</code></pre>

<hr>

<h2>120. Name Locator Final Checklist</h2>

<ul>

<li>Understand the HTML structure.</li>

<li>Identify the target element.</li>

<li>Find the <code>name</code> attribute.</li>

<li>Copy the exact name value.</li>

<li>Check whether the name is stable.</li>

<li>Check whether multiple elements share the same name.</li>

<li>Use <code>By.name()</code> when appropriate.</li>

<li>Use <code>findElements()</code> for groups.</li>

<li>Use another attribute such as <code>value</code> to distinguish elements when necessary.</li>

<li>Use explicit waits for dynamic elements.</li>

<li>Handle iframes before locating inner elements.</li>

<li>Use Page Object Model for larger projects.</li>

<li>Validate the expected result.</li>

</ul>

<hr>

<h2>121. Conclusion</h2>

<p>The <strong>Name Locator</strong> is an important Selenium WebDriver locator strategy used to identify elements through their HTML <code>name</code> attribute. Its basic Java syntax is <code>By.name("value")</code>.</p>

<p>Name Locators are particularly useful when working with forms, input fields, search boxes, textareas, buttons, radio buttons, checkboxes, and other controls that provide stable name attributes.</p>

<p>One important difference between Name and ID locators is that multiple elements can share the same <code>name</code> value. This is common with radio-button groups and checkbox groups. In such situations, <code>findElements()</code> can be used to retrieve the matching elements, after which attributes such as <code>value</code> can be checked to identify the required option.</p>

<p>For reliable Selenium automation, always inspect the HTML, verify the stability of the name attribute, use appropriate synchronization for dynamic content, and keep reusable locators organized through practices such as Page Object Model.</p>

<p>To learn more about Selenium WebDriver, locators, WebElements, TestNG, automation frameworks, and practical testing 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 explore or register for a course demo, visit <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a>.</p>

</div>

Previous Next
whatsapp