Element locators play an important part in interacting with elements in Selenium tests. Let me clarify here that Selenium supports lots of element locators like ID, Name, XPath, CSS Selectors, tagName, linkText, partialLinkText. All the element locators have their own advantages and disadvantages. Let us see what the tagName locator in Selenium, how it works, and when to use it in real-time test automation scenarios.
What is TagName Locator in Selenium?
By.ByTagName is an inner static class inside the By class in Selenium. It represents the By.tagName(String tagName) locator strategy.
TagName locator is a simple and very powerful element locator in Selenium. One can use it to locate an element by HTML tags such as <input>, <a>, <div>, <button>, <h1>, etc. It allows to interact with all the links on a page or loop through rows in a table. Also, you can use it to find elements of a specific tag type, either a single element or a group of them.
When and Why to Use TagName Locator?
There are many other power locators available in Selenium. So why or when to use the tagname locator?
Here are some real world scenarios where you can prefer to use it instead of other element locators.
Count the number of elements on the page using the tag name
Suppose you have a test scenario or requirement to count how many links or buttons are present on a page. You can count it easily using the tag name locator.
Here is an example in Java
// Find all elements with tag name 'a'
List<WebElement> links = driver.findElements(By.tagName("a"));
// Count the number of 'a' tags
int count = links.size();
// Print the count
System.out.println("Number of <a> tags on the page: " + count);
In the above example, findElements(By.tagName("a")) will find all elements with the <a> tag and size() gives the count of those elements.
When other element locators are not available
Sometimes, elements do not have any attribute but have a tag name only. In this case, it is easy to locate the element based on its tag name instead of slower element locators like XPath and CSS selectors.
Easy to find the child elements
You can use it to find a child element which is located inside a parent element, such as getting all rows <tr> from a table.
Here is an example in Python to read data from the table using tag name.
# Locate the table (optional if you want to focus on a specific table)
table = driver.find_element(By.ID, "customers")
# Find all rows (<tr>) inside the table
rows = table.find_elements(By.TAG_NAME, "tr")
# Print the number of rows
print(f"Total number of rows: {len(rows)}")
# Optional: Print the text in each row
for index, row in enumerate(rows):
print(f"Row {index}: {row.text}")
In this example, find_elements(By.TAG_NAME, "tr") will find all the <tr> elements (rows) inside that table. Then len(rows) will count the number of rows and row.text will get the text content of each row.
How TagName Works (Behind the Scenes)
When you use By.tagName() in Selenium test, it will search for your provided HTML tag name on the page
For example:
<a href="https://example.com">Click Me</a>
In this case, if you use By.tagName("a"), it finds the anchor element from the given HTML structure.
How to find the Tag Name of an element from the page
To find the tag name of the element, you can:
- Right click on element.
- Select inspect element.
You can get the tag name of the element as shown in the given image.
Java, Python, and C# Syntax to use TagName Locator in Selenium
Java syntax
//To find single element
WebElement element = driver.findElement(By.tagName("tagname"));
//To find multiple elements
List<WebElement> elements = driver.findElements(By.tagName("tagname"));
Python syntax
//To find single element
element = driver.find_element(By.TAG_NAME, "tagname")
//To find multiple elements
elements = driver.find_elements(By.TAG_NAME, "tagname")
C# syntax
//To find single element
IWebElement element = driver.FindElement(By.TagName("tagname"));
//To find multiple elements
IReadOnlyCollection<IWebElement> elements = driver.FindElements(By.TagName("tagname"));
Practical Examples of Using TagName Locator
Here are some examples of using the tagName locator to understand it better.
Example 1: Find a header tag using TagName
// Find the first <h1> tag on the page
WebElement heading = driver.findElement(By.tagName("h1"));
System.out.println("Heading Text: " + heading.getText());
In this example, it will locate the first h1 tag using By.tagName("h1") and get the header text using heading.getText() and print it in the console.
Example 2: Find All Links on a Web Page
// Find all <a> tags (links)
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
System.out.println("Total Links: " + allLinks.size());
for (WebElement link : allLinks) {
System.out.println(link.getText() + " - " + link.getAttribute("href"));
}
In the above example, findElements(By.tagName("a")) will find all elements having tag name a. allLinks.size() will calculate how many links and print it in the console. The next for loop is used to extract link text using link.getText() and print it in the console.
Example 3: Count All Input Fields on a Form
// Find all <input> fields
List<WebElement> inputFields = driver.findElements(By.tagName("input"));
System.out.println("Number of input fields: " + inputFields.size());
You can use the above example to calculate how many input fields are present on the page.
Step by step how to use tagName in Selenium
Step 1: Download and install browser driver
First of all, you need to download the browser driver, i.e. ChromeDriver, to run tests in Chrome browser. Here is a guide on how to download and configure Selenium Chrome Driver.
Step 2: Download and Configure Selenium in your project
Next step is to download and configure Selenium in your project. You can do it manually or use a Maven-like framework to set up Selenium. Here is step by step guide on how to download and install Selenium Webdriver with Eclipse.
Step 3 Launch browser and run test
Now you can use the following examples to run tests in Java, Python, and C# languages. These examples will demonstrate how to use the tagName in Selenium tests.
tagName Selenium Example in Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class TagNameExample {
public static void main(String[] args) {
// Set the path to your chromedriver executable if needed
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
// Step 3: Open a website
driver.get("https://example.com");
// Step 4: Find a single element by tag name
WebElement firstParagraph = driver.findElement(By.tagName("p"));
System.out.println("First paragraph text: " + firstParagraph.getText());
// Step 5: Find multiple elements by tag name
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
System.out.println("Total links: " + allLinks.size());
// Step 6: Close browser
driver.quit();
}
}
tagName Example in Python
from selenium import webdriver
from selenium.webdriver.common.by import By
# Step 1: Launch browser
driver = webdriver.Chrome()
# Step 2: Open a website
driver.get("https://example.com")
# Step 3: Find a single element by tag name
first_paragraph = driver.find_element(By.TAG_NAME, "p")
print("First paragraph text:", first_paragraph.text)
# Step 4: Find multiple elements by tag name
all_links = driver.find_elements(By.TAG_NAME, "a")
print("Total links found:", len(all_links))
# Step 5: Close browser
driver.quit()
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.ObjectModel;
class TagNameExample
{
static void Main()
{
// Step 1: Launch browser
IWebDriver driver = new ChromeDriver();
// Step 2: Open a website
driver.Navigate().GoToUrl("https://example.com");
// Step 3: Find a single element by tag name
IWebElement firstParagraph = driver.FindElement(By.TagName("p"));
Console.WriteLine("First paragraph text: " + firstParagraph.Text);
// Step 4: Find multiple elements by tag name
ReadOnlyCollection<IWebElement> allLinks = driver.FindElements(By.TagName("a"));
Console.WriteLine("Total links found: " + allLinks.Count);
// Step 5: Close browser
driver.Quit();
}
}
Advantages of the tagName locator
Here is a list of advantages of using tagName in your Selenium test.
Simple and Easy to Use
It is straightforward to locate elements by their HTML tag, like a, div, table, etc
Useful for Bulk Element Retrieval
Handy to collections of elements with the same tag name, like:
- All links on a page (<a>)
- All rows in a table (<tr>)
- All images (<img>)
Efficient for Common Scenarios
You can use the tag name locator when you are looking to loop through lists of similar elements, or iterate over table rows or cells.
No Need for Attributes
Other locators like ID, name, Class name need an attribute and a value. But you just need an HTML tag to locate an element by tag name.
Lightweight Selector
It is a lightweight selector compared to XPath and CSS selectors.
Limitations of TagName Locator
Each and every locator has its own strength and limitations. Same way, finding by tagName has its own limitations as below.
Not Specific Enough
Common tags like div, span, and a can appear many times, so findElement() will return only the first matching element. Also, it is hard to target specific elements without combining it with other locators.
Limited Filtering
Using tagName, direct filtering by attributes like id, class, name is not possible.
Can Return Empty Results
findElements() will return an empty list and findElement() will throw a NoSuchElementException if the tag is not present on the page.
May Impact Performance
If there are lots of matching tags on the same page, it is not advised to use tagName as a locator. It can impact performance.
Frequently Asked Questions (FAQs)
- You want to find all elements of a certain type (e.g., all links <a>, all images <img>).
- You are working with tables (e.g., rows <tr>, cells <td>).
- There’s no unique attribute like ID or Class available.
- findElement(By.tagName()) will throw a NoSuchElementException.
- findElements(By.tagName()) will return an empty list/collection.
- By.tagName() will search by the HTML tag and not by the attributes.
- It will return many elements, whereas By.id() or By.name() usually return unique elements.
- a → links
- img → images
- div → containers
- span → inline elements
- p → paragraphs
- table, tr, td → tables
- h1, h2, etc. → headings
- input, button → form elements
Common Errors & Troubleshooting
Best Practices
- Use TagName for Groups: Finding element by tagName is best to find multiple similar elements.
- Narrow the Search Scope: To interact with a child element, first locate the parent element and then use tagName inside them to avoid unwanted matches.
- Always Use Lowercase Tags: Use tag name in lower case to reduce unwanted errors.
- Handle Empty Lists: When using findElements(), check for empty list before performing actions.
- Switch to Frames/Windows: If you are working with multiple frames or windows, first of all, switch focus on them before performing any action.
tagName is a very useful locator in Selenium if used in correct scenarios.
Have any questions or queries? You can ask me in a comment below. I will try my best to answer you.
No comments:
Post a Comment