How to find an element using the attribute “name” in Selenium?


We can find an element using the attribute name with Selenium webdriver using the locators - name, css, or xpath. To identify the element with css, the expression should be tagname[name='value'] and the method to be used is By.cssSelector.

To identify the element with xpath, the expression should be //tagname[@name='value']. Then, we have to use the method By.xpath to locate it. To locate an element with a locator name, we have to use the By.name method.

Let us look at the html code of an element with name attribute −

Syntax

WebElement e = driver. findElement(By.name("q"));
WebElement m = driver. findElement(By.xpath("//input[@name = 'q']"));
WebElement n =
driver. findElement(By.cssSelector("input[name='q']"));

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorName{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.google.com/");
      // identify element with name
      WebElement k = driver.findElement(By.name("q"));
      k.sendKeys("Selenium");
      //identify element with css
      WebElement p = driver.
      findElement(By.cssSelector("input[name='q']"));
      String st = p.getAttribute("value");
      System.out.println("Attribute value: " + st);
      //identify element with xpath
      WebElement o = driver.
      findElement(By.xpath("//input[@name='q']"));

      o.clear();
      driver.quit();
   }
}

Output

Updated on: 03-Apr-2021

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements