Software Development and QA Tips By QASource Experts

How To Use TagName Locator in Selenium Automation Scripts?

Written by Timothy Joseph | May 30, 2022 4:00:00 PM

There are multiple selenium locators which are used during the course of automation to locate the web elements on a web page. Below is the list of locators:

  • ID
  • Name
  • Class
  • TagName
  • Xpath
  • CSS selectors

From the above-mentioned list, usually, automation testers prefer other locators over tagName. Let us discuss some usage and real-time examples of using tagName in the automation scripts:

A tagName is a part of the DOM structure where all the web elements on the page are defined by tags like input for text fields, a button for buttons field, etc.

 

Usage:

TagNames are used where we don't have attributes like Name, ID, class, then it is recommended to use tag names to locate the web elements.

Below are the few real time examples for using tagNames in selenium:

  • Generic syntax for locating a web element:

    driver.findElement(By.tagName (<htmltagname>))
  • Scenario 1:

    When you have to locate any textbox, then below is the Syntax for locating a textbox:
    driver.findElement(By.tagName (<Input>))
  • Scenario 2:

    Below is the syntax used for locating a button on any webpage:
    driver.findElement(By.tagName (<button>))
  • Scenario 3:

    Syntax for locating an image:
    driver.findElement(By.tagName("img"));
  • Scenario 4:

    Syntax for locating the number of rows:
    driver.findElements(By.tagName("tr"));

    Apart from this, <td> and <tr> tags are used to retrieve data from the table. Anchor tags are used to locate the links on the web page.

When you are locating a web element via tagNames then it identifies all the elements and will return the first tag match, this is the only reason, automation testers are preferring other locators over tagName.

Hoping this will help you to understand the usage of tagName.