Selenium Find Element using By.Name() Example
Selenium Find Element using By.Name() Example
In this tutorial, we will learn to find element on a web page using the attribute Name of the page element. We can use the By.name() method to locate the element with name attribute.
We will test the TestLink Login page in this example. TestLink is an open-source Testcase Management application.
Inspect Elements
We can identify the elements using the name attribute. The most easiest way is to use respective browser Developer tools to find out the different attributes of the element on the web page. However we can use, View source option of the web page as well.
To inspect elements using Firefox Web Developer Tools, follow this link:
https://www.testingdocs.com/inspect-elements-using-firefox-web-developer-tools/
We can see that the HTML code for the Login name text box in the form is:
<input maxlength=”100″ name=”tl_login” id=”tl_login” type=”text” class=”form__input” placeholder=”Login Name” required=””>
The name of the element is defined as name=“tl_login”. The input parameter for the method is By.name() is tl_login. Note that for this element both the id and the name attributes are same.
For Example,
By.name(“tl_login”)
Environment and Tools
The environment and the tools used in this example:
- JDK
- Maven build tool
- Selenium Webdriver
- Eclipse IDE
- Firefox Web browser Tools
- Windows 10
Code Listing
The complete code listing for the test is as follows:
package com.testingdocs.tests; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.openqa.selenium.By; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; // Selenium Tutorials - www.TestingDocs.com public class FindByNameExampleTest { public WebDriver driver; @BeforeClass public void setUp() throws MalformedURLException { DesiredCapabilities dCaps = new DesiredCapabilities(); dCaps.setBrowserName("chrome"); driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), dCaps); } @Test public void testNameLocator() throws InterruptedException { driver.navigate() .to("http://localhost/testlink/login.php"); driver.manage().window().maximize(); try { driver.findElement(By.name("tl_login")) .sendKeys("Hello"); driver.manage().timeouts() .implicitlyWait(45, TimeUnit.SECONDS); System.out.println("Typed Hello in Login Username..."); } catch (Exception e) { System.out.println(e.getMessage()); } } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
In this example, we have used TestLink Login page on localhost. The username
driver.findElement(By.name(“tl_login”)).sendKeys(“Hello”);