The By.tagName()
locator in Selenium is used to identify web elements by their HTML tag name. This is especially useful when you want to select elements like <input>
, <button>
, <a>
, or <div>
when no other unique attributes are available.
π What is a Tag Name?
A tag name refers to the name of the HTML element, such as input
, button
, a
, div
, etc.
<input type="text" name="username" />
<button type="submit">Login</button>
<a href="/home">Home</a>
✅ When to Use By.tagName()?
- ✅ When you want to count elements of a certain type
- ✅ When you're working inside a parent element and need children by tag
- ✅ When testing elements like all links, buttons, or list items
π Syntax in Java
driver.findElement(By.tagName("tagname"));
To fetch multiple elements of the same tag:
driver.findElements(By.tagName("tagname"));
π» Example: Fetch All Links on a Page
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 LinksExample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
// Get all anchor (link) elements
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
System.out.println("Total links found: " + allLinks.size());
for (WebElement link : allLinks) {
System.out.println(link.getText() + " - " + link.getAttribute("href"));
}
driver.quit();
}
}
π§ͺ Example: Access Table Rows
If you want to get all rows from a table:
WebElement table = driver.findElement(By.id("userTable"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
for (WebElement row : rows) {
System.out.println(row.getText());
}
✅ Best Practices
- πΈ Use
By.tagName()
when other locators like ID, name, or class are unavailable. - πΈ Combine with parent elements to narrow down results.
- πΈ Avoid relying solely on tag names when elements are not unique.
⚠️ Common Mistakes
Mistake | How to Avoid |
---|---|
Using findElement() when multiple elements exist |
Use findElements() to avoid missing results |
Accessing tag without scoping inside a container | Use parent element’s findElements() to restrict search area |
Assuming tags are unique | Verify with browser inspection or DevTools |
π Summary
By.tagName()
allows locating elements using standard HTML tags.- Best for selecting all elements of a type like
<a>
,<input>
,<tr>
, etc.- Use
findElements()
when expecting multiple results.
π Keep Learning
Explore other locators in Selenium: