findElement by tagName in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class FindElementByTagNameTest { public static void main(String[] args) { // Set path to chromedriver if needed // System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com"); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // Wait until the <h1> element is visible WebElement h1Element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("h1"))); // Assert that the element is displayed if (!h1Element.isDisplayed()) { throw new AssertionError("<h1> element is not displayed"); } // Assert that the text is exactly 'Welcome to Example' String expectedText = "Welcome to Example"; String actualText = h1Element.getText(); if (!actualText.equals(expectedText)) { throw new AssertionError(String.format("Expected text '%s' but found '%s'", expectedText, actualText)); } System.out.println("Test passed: <h1> tag found with correct text."); } finally { driver.quit(); } } }
This test script uses Selenium WebDriver with Java to automate the manual test case.
First, it opens the Chrome browser and navigates to the homepage URL.
It uses an explicit wait to wait up to 10 seconds for the <h1> element to be visible on the page, ensuring the page has loaded the element.
Then it checks if the element is displayed on the page. If not, it throws an assertion error.
Next, it verifies the text inside the <h1> tag exactly matches 'Welcome to Example'. If the text differs, it throws an assertion error with a clear message.
If both checks pass, it prints a success message.
Finally, it closes the browser to clean up resources.
This approach follows best practices by using explicit waits, proper locators, and clear assertions.
Now add data-driven testing to verify the <h1> text for 3 different URLs with their expected <h1> texts.