How to Get Element by Tag Name In Selenium

Vipul Gupta

Posted On: June 6, 2024

view count206281 Views

Read time17 Min Read

Selenium locators are essential for locating elements on a web page. Among the locators available, such as className, CSS Selector, ID, linkText, partialLinkText, tagName, and XPath, users can choose any locator that fits their needs to locate web elements. While className, CSS selector, ID, and XPath are more frequently used by testers and developers, the tagName() locator is particularly useful for selecting elements based on their HTML tag.

This can be helpful when you want to interact with elements like all the links ( <a>tags), all the buttons ( <button> tags), or any other specific HTML tags on a web page. Despite its usefulness, the tagName() locator is less commonly used and has less working experience than other locators in Selenium.

What Is a Tag Name Locator in Selenium?

A tag name is an integral part of an HTML Document Object Model (DOM) structure, representing different elements on a web page, such as input, button, and anchor tags. These HTML tags can have multiple attributes, including id, name, and class name.

The tagName() locator in Selenium uses the tag name to find elements without relying on these attributes. This method allows you to locate all aspects of a specific type, such as all buttons or all links, on a web page. The tagName() locator is particularly useful when extracting or interacting with the content within a specific tag.

However, Selenium WebDriver provides support for various WebElement locators in Selenium. These locators help identify elements on a web page and interact with them. Each WebElement locator can locate any HTML element on a web page differently, depending on the specific use cases.

Locator Syntax Usage
id driver.findElement(By.id(“ <id_attribute_value> ”)); Allows to locate WebElement using the id attribute
name driver.findElement(By.name(“ <name_attribute_value>”)); Allows to locate WebElement using the name attribute
className driver.findElement(By.className(“ <class_attribute_value>”)); Allows to locate WebElement using the class attribute
linkText driver.findElement(By.linkText(“ <actual_hyperlink_text>”)); Allows to locate WebElement using the actual hyperlink text
partialLinkText driver.findElement(By.partialLinkText(“ <partial_hyperlink_text>”)); Allows to locate WebElement using the part of hyperlink text
tagName driver.findElement(By.tagName(“ <HTML_tag>”)); Allows to locate WebElement using the HTML tag
cssSelector driver.findElement(By.cssSelector(“ <css_value>”)); Allows to locate WebElement using the CSS selector value
xpath driver.findElement(By.xpath(“ <xPath_value>”)); Allows to locate WebElement using the Xpath value

Navigating to the correct WebElement is important to perform any actions. You must know how to inspect the element on Mac and Windows or any OS you choose. To learn how to interact with WebElements in Selenium, watch the complete video tutorial and gain practical insights.

You can Subscribe to the LambdaTest YouTube Channel to get more video tutorials on other Selenium testing techniques, various automation testing tools, and more.

To effectively use the tagName(), locator, it is essential to understand when to apply it for accessing elements and how to get elements by tag name on a web page.

When To Use Tag Name Locator in Selenium?

The tagName() locator in Selenium is used to identify elements using tag names like <div>, <table>, <h1>, and so on. You might wonder when to use the tagName() locator in Selenium. It is particularly useful when attribute values such as id, class, or name are unavailable. In such cases, you can rely on the tagName() locator to locate a WebElement.

For example, if you wish to retrieve data from a table, you may use <td> tag or <tr> tag to retrieve data.

Similarly, when you wish to verify the number of links and validate whether they are working, you can choose to locate all such links using the anchor tag (<a> tag).

One important thing to note is that using a tagName() locator may lead to multiple elements being identified due to similar tags. In such cases, Selenium will select the first tag that matches the provided locator.

Therefore, be mindful when using tagName() locators in Selenium.

The Selenium WebDriver provides two methods to locate web elements on a webpage.

  • findElement(): To find a single WebElement and return it as an object of WebElement. If there are multiple matching WebElements, the first occurrence is returned.
  • findElements(): To find all the matching WebElements and return them as a list of WebElements.

If you intend to locate a single element, use the findElement() function, which returns the first occurrence. If you need to locate all elements with matching tags, use the findElements() function, which returns a list of WebElements. You can learn more about these functions through this blog on findElement() and findElements() in Selenium.

Info Note

Run your tests across 3000+ browsers and OS combinations. Try LambdaTest Today!

Now that we have learned the tagName() locator and when to use it, we will demonstrate how to get elements by tag name to identify and locate web elements on a web page.

Demonstration: Find the First WebElement Using the tagName()

For demonstration purposes, we will execute all the further test cases or scenarios using a cloud testing platform to leverage the true capability of automation testing and to scale the test process.

Cloud testing platforms like LambdaTest allow businesses to test their applications in a virtual environment, replicating real-world scenarios without a physical hardware setup. LambdaTest is an AI-powered test orchestration and execution platform that lets you run manual and automated tests at scale with over 3000+ real devices, browsers, and OS combinations.

This platform provides a robust test infrastructure where you can perform web application testing using various automation testing frameworks like Selenium, Cypress, Playwright, and more.

Before we use this approach to get element by tag name, it’s essential to set up your project and write a test script. This script should use the findElement() function in Selenium WebDriver to fetch the first matching WebElement by tag name.

Additionally, you can use the findElements() function to get a list of all matching WebElements by tag name. By leveraging these functions, you can efficiently interact with elements like links (<a> tags), buttons ( <button> tags), and other specific HTML tags on a web page.

Project Setup:

For demonstration purposes, we will use the Eclipse IDE to create the project, with Java as the programming language and TestNG as the automation testing framework. We will create the project with Maven, which uses a POM file to store the project dependencies.

However, if you are just starting with Selenium testing, you can follow this guide on getting started with Maven for Selenium testing to learn everything you need to know about Maven and why it is required when creating projects with Java.

The same project setup is used for all the test scenarios that will be executed. To add a test case for each scenario, we will only add a new Java class file. Therefore, carefully follow the setup to prevent any errors.

To get started, follow the steps below.

Step 1. Launch Eclipse IDE and create a Maven project called GetElementByTagNameSelenium.

Step 2. As the project uses TestNG in Selenium, add the latest stable versions of Selenium 4 and TestNG dependencies inside the pom.xml. You can find the latest dependencies from the Maven repository.

Update the pom.xml with the dependencies; it should look as shown below.

Next, create a Java class file called BaseTest.java. This Java file contains all the common code for test execution, like setup and initializing the WebDriver, declaring and initializing public variables for the project, handling driver termination after test completion, connecting to LambdaTest cloud grid for execution, and more.

Before checking the test results, let’s understand the code present in BaseTest.java in detail.

Code Walkthrough:

  1. Create an object of RemoteWebDriver and initialize it as null.
  2. Create an object of RemoteWebDriver and initialize it as nul

  3. Fetch your Username and Access Key for the LambdaTest by navigating to Account Settings > Password & Security and provide the same to the cloud grid for test execution.
  4.  navigating to Account Settings  Password & Security

    Alternatively, you can configure these as environment variables and directly fetch them in code.

    For Windows:

    For macOS and Linux:

  5. Create a string variable as status and initialize it with value as failed. This will be used to update the test status on the LambdaTest dashboard after each test is executed.
  6. Create a string variable as status and initialize it with value as failed.

  7. Add the first method as setup() and annotate it with @BeforeTest to execute it before each test.
  8. Add the first method as setup()

  9. Start by creating an object of the ChromeOptions() class to set the required browser properties for running tests. This can be used to set the OS and browser versions. We are using the latest available versions here.
  10. creating an object of the ChromeOptions()

  11. To specify the additional browser capabilities required by the LambdaTest platform for execution on their cloud grid, use a HashMap type variable. This will help identify the dashboard test results using the build name and other details.
  12. additional browser capabilities required by the LambdaTest platform

  13. Fetch the required browser capabilities from the LambdaTest platform by navigating to the LambdaTest Capabilities Generator. This provides ready-to-use code for setting up browser capabilities, and you can set up other configurations that your test should have that can be used in the execution.
  14. browser capabilities from the LambdaTest platform

  15. Use the Selenium RemoteWebDriver to connect to the LambdaTest remote grid using your credentials and the ChromeOptions object, which contains all specified browser capabilities.
  16. Selenium RemoteWebDriver to connect to the LambdaTest remote grid

  17. Add another method closeDriver(), to quit the driver instance after each test. For this, use the @AfterTest annotation to execute it after each test execution. Also, this method executes the script to update the status on the LambdaTest dashboard before quitting the WebDriver.
  18. To learn more about various annotations for better prioritizing the test cases, follow this guide on TestNG annotation in Selenium.

    various annotations for better prioritizing the test cases

    In the above section, we set up the required dependencies and libraries in the pom.xml file and the BaseTest.java file. Now, we will look into the test scenarios we will execute to understand how to get elements by tag name.

    The test scenario below is one that we will be executing to understand how to get elements by tag name using findElement() with tagName() locator.

    Test Scenario:

    1. Navigate to LambdaTest eCommerce Playground.
    2. Fetch the first WebElement using the tagName() locator for the HTML tag <h4>.
    3. Get the text for the WebElement and print it.

    Below is the code implementation for the test scenario to get the first WebElement by tag name in Selenium.

    Before we jump to the result, let’s look into the code above to understand how it works step-by-step.

    Code Walkthrough:

    1. Create the test class and inherit BaseTest.java to use the common WebDriver’s functions.
    2. Create the test class and inherit BaseTest.java

    3. Add the test case and name it as testFindFirstElementByTagName(). Annotate it with @Test annotation, as we are using TestNG to execute the cases.
    4. Add the test case and name it as testFindFirstElementByTagName()

    5. Navigate to the LambdaTest eCommerce Playground.
    6. Navigate to the LambdaTest eCommerce Playground

    7. Fetch the first element using the driver.findElement(By.tagName)and use the tag <h4> tag. As you want to locate only the first WebElement, the findElement() function of webDriver is used here.
    8. Fetch the first element using the driver.findElement(By.tagName)

    9. Print the text of the WebElement located in the previous step.
    10. Print the text of the WebElement located

    11. Update the value of the status variable to pass to showcase that we encountered no errors and that the execution was successful.
    12. Update the value of the status variable to pass

      Output:

      Executing the above test to get the first WebElement by tagName() locator in Selenium will give output on the console like the one shown below.

      Executing the above test to get the first WebElement

      Result:

      The test execution logs on the LambdaTest Dashboard can be viewed under the Automation > Web Automation section.

      test execution logs on the LambdaTest Dashboard

      To learn more about performing automation testing on the LambdaTest platform, watch the video tutorial below and get started on your automation testing journey.

      We have learned how to get elements by tag name to fetch the first WebElement using the findElement() method with the tagName() locator property. Next, we will use the findElements() method to return all the matching WebElements in a list using the tagName() locator property, along with a code demonstration.

      Demonstration: Find All WebElements Using the tagName()

      Now, let us understand how to get elements by tag name to locate all the WebElements using the tagName() locator. As mentioned before, we will use the same BaseTest.java file that consists of the same code as used in the above demonstration.

      Below is the test scenario we will execute to understand how to get elements by tag name using findElements() with tagName() locator.

      Test Scenario:

      1. Navigate to LambdaTest eCommerce Playground.
      2. Fetch all the matching WebElements using tagName() locator for the HTML tag <h4> and store it in a list.
      3. Print the total number of located WebElements.
      4. Traverse the entire list and print the text for each WebElement.

      You must create a new file named TestFindAllElementsByTagName.java to write your test script for the test scenario above.

      github

      Code Walkthrough:

      1. Add the next test class file to understand the implementation of locating all the elements by using tagName(). Name it at TestFindAllElementByTagName and inherit BaseTest.java.
      2. next test class file to understand the implementation of locating

      3. Add the test method and annotate it with @Test annotation.
      4. Add the test method and annotate it

      5. Navigate to the LambdaTest eCommerce Playground.
      6. Navigate to the LT eCommerce Playground

      7. Fetch all the elements using the h4 tag on the webpage. For this, we use the findElements() method of the Selenium WebDriver. Store this list of WebElements in the List variable.
      8. Fetch all the elements using the h4 tag on the webpage

      9. Print the total number of located WebElements using the tagName() locator using the size() method.
      10. total number of located WebElements using the tagName()

      11. Traverse the entire list of webElements to print the text of each located element.
      12. entire list of webElements to print the text of each located element

      13. Update the value for the status variable as passed.
      14. Update the value for the status variable as passed

        Output:

        Executing the above test to get all the WebElements by tagName() locator in Selenium will give the output on the console like the one shown below.

        Executing the above test

        get all the WebElements by tagName()

        Result:

        The test execution results will be displayed on the LambdaTest Dashboard, which can be viewed under the Automation > Web Automation section.

         test execution results will be displayed on the LambdaTest Dashboard

        Conclusion

        With this, we have come to the end of this blog on how to get elements by tag name in Selenium with Java. We have used the tagName() locator in Selenium on different scenarios to fetch the first and all matching elements. We learned when to use the tagName() locator, and this will help you to use it more effectively and write reliable, robust automation test scripts. Now, it is time for you to go ahead and start using it in your scripts and explore if it can be used in combination with other locators. Happy locating !!

        Frequently Asked Questions (FAQs)

        What is the purpose of WebElement?

        WebElement is an HTML interface element allowing users to interact with them using Selenium WebDriver. It allows users to perform several actions, like clicking, submitting, entering data, and asserting as required.

        What are the top web element locators in Selenium?

        Mostly 8 web element locators are used in Selenium. These are ID, Name, className, tagName, linkText, partialLinkText, CSS Selector, and XPath.

        What is the best way to find the total number of matching elements with a tag?

        If all the matching elements are located using the findElements() method, then the size() function of the Java util class can easily find the total number.

        Which is the best web element locator and why?

        ID is considered the best web element locator because, as per the web development standards, the ID of all the elements is unique on the web page, making it safe from any issues.

        What is a locator, and how is it different from a WebElement?

        Locator is how to identify and access a web element on the webpage. Locators are used to perform actions on web elements using Selenium WebDriver. However, a web element, on the other hand, is an HTML element on a webpage. A WebElement can be a textbox, checkbox, dropdown box, label, header, title, button, etc.,

        What makes an ideal locator?

        An ideal locator should be unique to the desired element and use minimal information or text related to the locator that might get changed.

Author Profile Author Profile Author Profile

Author’s Profile

Vipul Gupta

Vipul Gupta is a passionate Quality Engineer with 6+ years of experience and keen interest in automation testing of Web and API based applications. He is having experience in designing and maintaining various automation frameworks. Currently working as Sr. SDET, he enjoys reading and learning about new test practices and frameworks.

Blogs: 22



linkedintwitter