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


We can find an element using the element tag name with Selenium webdriver with the help of locator tagname. To locate an element with tagname, we have to use the By.tagName method.

In the html code, a tagname is usually enclosed by <>, for example, an anchor tag <a> represents links on the page. An input tag represents text boxes, checkboxes or radio buttons. Let us look at the html code of an element and try to identify it with its tagname −

In the above image, the text – You are browsing the best resources for has the h4 tag.

Syntax

WebElement e = driver. findElement(By.tagName("h4"));

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 LocatorTagName{
   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.tutorialspoint.com/index.htm");
      // identify element with tag name
      WebElement n = driver.findElement(By.tagName("h4"));
      //obtain text on element
      String s = n.getText();
      System.out.println("Text on element is : " + s);
      driver.close();
   }
}

Output

Updated on: 06-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements