0
0
Selenium Javatesting~10 mins

findElement by tagName in Selenium Java - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage, finds the first <h1> tag on the page using findElement(By.tagName), and verifies that the heading text matches the expected value.

Test Code - JUnit with Selenium WebDriver
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class FindElementByTagNameTest {
    private WebDriver driver;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
    }

    @Test
    public void testFindH1ByTagName() {
        driver.get("https://example.com");
        WebElement heading = driver.findElement(By.tagName("h1"));
        String headingText = heading.getText();
        assertEquals("Example Domain", headingText);
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready-PASS
2Navigate to https://example.comBrowser displays the Example Domain webpage with a visible <h1> heading-PASS
3Find the first <h1> element using driver.findElement(By.tagName("h1"))The <h1> element with text 'Example Domain' is locatedVerify the <h1> element is found and not nullPASS
4Get the text of the <h1> elementText 'Example Domain' is retrieved from the <h1> element-PASS
5Assert that the heading text equals 'Example Domain'The heading text matches the expected stringassertEquals("Example Domain", headingText)PASS
6Close the browser and end the testBrowser window is closed-PASS
Failure Scenario
Failing Condition: The <h1> tag is not found on the page or the text does not match 'Example Domain'
Execution Trace Quiz - 3 Questions
Test your understanding
What does driver.findElement(By.tagName("h1")) do in this test?
AFinds all <h1> elements on the page
BFinds the first <h1> element on the page
CFinds an element by its ID 'h1'
DFinds an element by its class name 'h1'
Key Result
Always verify that the element you find by tag name exists and contains the expected text to ensure your test checks the correct page content.