About this lesson
By.tagName in Selenium Java: find elements by their HTML tag
Learn Selenium JavaBeginnerLocators
How it works
By.tagName("h2") matches elements by their HTML tag. Tag names in an HTML page are case-insensitive, so h2 and H2 find the same heading. On its own it is a blunt instrument, because most tags appear many times; on Text Fields there are seven input elements, and field 3 is a textarea.
It shines in two situations. One is a tag that occurs once on the page, like the single h2 heading here. The other is searching inside an element you already have: calling findElements(By.tagName("td")) on a table row returns just that row's cells, which the table lessons rely on.
About the assignment
The Text Fields page has exactly one h2, the page heading. You will locate it by tag name and print the text a reader sees on the page.
What you will do
- Locate the heading with
driver.findElement()andBy.tagName(). - Read its visible text with
getText(). - Print the text after the label
Heading:.
Common mistakes
Assuming the first tag is the one you want
By.tagName("label")on this page returns the first label, the one for field 1. A tag locator gives no way to say which occurrence you meant, so narrow it with a parent element or switch to CSS.Reading the wrong page's heading
Headings are not reliable page identifiers. On the Text Messages practice page the
h2also says Text Fields, because it was copied; the window title is a better check of where you are.Using getAttribute("text")
Visible text is not an attribute.
getAttribute("text")returnsnullfor a heading, whilegetText()returns what is rendered.
In a real test suite
Tag locators mostly appear in scoped searches: rows inside a table, option elements inside a select, li items inside one menu. Searching the whole page by tag is usually a sign that a better locator exists.
Lesson 8 introduces a locator that only works on one tag, the a element, and matches it by the text of the link.
Related lessons
- Read Table Headers with findElements()A scoped tag search: every
thinside one table. - Get Element Text with getText()More on
getText()and how it treats spaces and nested tags. - Find Multiple Elements with findElements()Return every match of a tag instead of only the first.
To try one of these calls on any page without a task, open the Online Selenium Java Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/TextFields");
// TODO: Find the h2 element by tag name
// TODO: Print its text in format: "Heading: <text>"
driver.quit();
}
}