How To Use Name Locator In Selenium Automation Scripts?
Tags: showdev, wev, devops, writing
Published: 2019-04-10 14:42:50



Locators in Selenium play an important role in the life of an automation engineer. Depending on how skilled you are in locating an element is directly proportional to the stability and efficiency of your automation testing with Selenium. There are multiple ways of utilizing locators in Selenium to find an element on a page but deciding the right one, does the business. In this article, I will be referencing on how to use by.name locator in Selenium automation scripts.

If you’re new to Selenium and wondering what it is then we recommend checking out our guide — [What is Selenium?](https://www.lambdatest.com/selenium?utm_source=devto&utm_medium=organic&utm_campaign=aug30_sd&utm_term=sd&utm_content=webpage)

If you are an advanced or medium Selenium practitioner, then you can chuck on dedicated articles mentioned above. And go for our complete guide to help you illustrate the practical demonstration of CSS locator in Selenium.

## Understanding The DOM(Document Object Model)

The Document Object Model(DOM) defines the structure of a webpage which constitutes of various tag elements and their corresponding attributes. For example, below shows the LambdaTest login page:

![](https://cdn-images-1.medium.com/max/2738/0*MLjARKX1YsXcOeE0.png)

In the screenshot above, we are trying to locate the ‘email’ field. The DOM structure of the email field is displayed below:

< input type="email" name="email" value="" placeholder="Email" required="required" autofocus="autofocus" class="form-control mt-3 form-control-lg" >

The attributes for the above DOM structure are:

* Type

* Name

* Value

* Placeholder

* Required

* Autofocus

* Class

***Hey! For [selenium testing tool](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=aug30_sd&utm_term=sd&utm_content=webpage), click here. Test on Selenium Grid Cloud of 3000+ Desktop & Mobile Browsers.***

## Understanding The By.name Locator In Selenium

By.name Selenium locator is used to identify the elements of a webpage. This attribute can be mentioned as part of multiple tags like < input >, < button >, < select > etc. Unlike ID, this may or may not be unique to a page. A webpage may contain multiple tags with the same By.name attribute value. In such a case, if your intent is to select your desired element, the By.name locator in Selenium may not be the correct choice.

A key point to note is when you tend to select an element with a desired name attribute value, it will select the first element it encounters. You may come across another scenario, where you wish to select elements with the same name attribute value, in this case, the **By.name** locator in Selenium may work using the **findElements** syntax. I will show both scenarios example in the code as we go ahead in the article.

In order to locate element via the By.name locator in Selenium, we use the below command:

driver.findElement(By.name(“Element NAME”));

Let’s dig into the code snippet to understand the usage of the By.namelocator.

![](https://cdn-images-1.medium.com/max/2000/0*zIT0OX_SuZzX3b4i.png)

This certification is for anyone who wants to stay ahead among professionals who are growing their career in Selenium automation testing.

Here’s a short glimpse of the Selenium 101 certification from LambdaTest:

{% youtube qx9FPFfJm7E %}

***How to choose the right [automation testing tool](https://www.lambdatest.com/blog/automation-testing-tools/?utm_source=devto&utm_medium=organic&utm_campaign=aug30_sd&utm_term=sd&utm_content=blog)? Check out this blog to select the right tools for automation testing.***

## Test Scenario 1 For By.nameLocator In Selenium

In the below code example, we are logging on to the LambdaTest platform. Here we will locate the ‘email’ and ‘password’ field using the By.name attribute.

    package Chromedriver;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class Name_Locator {

    public static void main(String[] args) {
            
            //Setting up chrome using chromedriver by setting its property
            System.setProperty("webdriver.chrome.driver", "C:\\Users\\navyug\\workspace\\Lambdatest\\src\\Chromedriver\\chromedriver.exe"); 
            
            //Opening browser
            WebDriver driver= new ChromeDriver() ;
            
            //Opening window tab in maximize mode
            driver.manage().window().maximize();
            
            //Opening application
            driver.get("[https://accounts.lambdatest.com/login](https://accounts.lambdatest.com/login)");
            
            //Locating the email field element via Name tag and storing it in the webelement
            WebElement email_field=driver.findElement(By.name("email"));
            
            //Entering text into the email field
            email_field.sendKeys("[sadhvisingh24@gmail.com](mailto:sadhvisingh24@gmail.com)");
            
            //Locating the password field element via Name tag and storing it in the webelement
            WebElement password_field=driver.findElement(By.name("password"));
                    
            //Entering text into the password field
            password_field.sendKeys("LoremIpsum");
            
            //Clicking on the login button to login to the application
            WebElement login_button=driver.findElement(By.xpath("//button[text()='LOGIN']"));
            
            //Clicking on the 'login' button
            login_button.click();
            
            //Closing the window
            driver.close();
            }
    }

***Hey! Perform live-interactive cross browser testing on [Safari for windows](https://www.lambdatest.com/safari-browser-for-windows?utm_source=devto&utm_medium=organic&utm_campaign=aug30_sd&utm_term=sd&utm_content=webpage) here.***

## Test Scenario 2 For By.name Locator In Selenium

In the below code example, post-logging in, under the automation section of the menu bar, we have a page where two web elements containing radio button have the same By.name attribute value as radio. We intend to switch between these two buttons. Below is the DOM structure for both those elements:

    &lt; div class="TimelineTab_viewRadioButton__18Zf3"&gt;
    &lt; label &gt;<input type="radio" name="radio" value="build_view"><span class="TimelineTab_labelText__2DZ00 TimelineTab_font14__2K4jw">Build View</span>
    <!-- label-->&lt; label&gt;&lt; input type="radio" name="radio" value="test_view"&gt;
    <span class="TimelineTab_labelText__2DZ00 TimelineTab_font14__2K4jw">Test View<!-- span--><!-- label -->&lt; /div &gt;</span>

The code snippet below:

    package Chromedriver;

    import java.util.List;
    import java.util.concurrent.TimeUnit;

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class Multiple_Name_Values {

    public static void main(String[] args) {

    //Setting up chrome using chromedriver by setting its property
                    System.setProperty("webdriver.chrome.driver", "C:\\Users\\navyug\\workspace\\Lambdatest\\src\\Chromedriver\\chromedriver.exe"); 
                    
                    //Opening browser
                    WebDriver driver= new ChromeDriver() ;
                    
                    //Opening window tab in maximize mode
                    driver.manage().window().maximize();
                    
                    //Maintaining an implicit wait for the entire application in case of throttling network or DOM not loaded
                    driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                    //Opening application
                    driver.get("[https://accounts.lambdatest.com/login](https://accounts.lambdatest.com/login)");
                    
                    //Locating the email field element via Name tag and storing it in the webelement
                    WebElement email_field=driver.findElement(By.name("email"));
                    
                    //Entering text into the email field
                    email_field.sendKeys("[sadhvisingh24@gmail.com](mailto:sadhvisingh24@gmail.com)");
                    
                    //Locating the password field element via Name tag and storing it in the webelement
                    WebElement password_field=driver.findElement(By.name("password"));
                            
                    //Entering text into the password field
                    password_field.sendKeys("LoremIpsum");
                    
                    //Clicking on the login button to login to the application
                    WebElement login_button=driver.findElement(By.xpath("//button[text()='LOGIN']"));
                    
                    //Clicking on the 'login' button
                    login_button.click();
                    
                    //Click on the Automation menu link on the sidebar
                    driver.findElement(By.xpath("//*[[@id](http://twitter.com/id)='app']/header/aside/ul/li[4]/a/span")).click();

    //Finding all the webelement on the page with name attribute value as radio
                    List<webelement> radio_button=driver.findElements(By.name("radio"));
                    
                    //Click on the test view of the element
                    radio_button.get(1).findElement(By.xpath("//span")).click();
                    
                    //Closing the driver
                    driver.close();
        }
    }
    </webelement>

As you can see in the above two examples, we have used the By.name locator in different ways. One was via **findElement** and the other was via **findElements command**. In one, our target was to locate a single element while in the other we located multiple elements with the same By.name and attempted to switch to one of those elements. So as per defined need and business, we can use the By.name locator. By.name locators are easy to use and maintain, the trick lies in identifying their right usage.

You can also read my previous article where I have explained the demonstration of all the locators in Selenium WebDriver. I will also be writing down a series of dedicated articles to demonstrate thorough usage of each locator of Selenium in detail. Stay tuned! 🙂