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.
Practice
findElement(By.tagName("button")) do?Solution
Step 1: Understand the method purpose
findElementreturns the first matching element found by the locator.Step 2: Analyze the locator type
By.tagName("button")looks for elements with the tag <button>.Final Answer:
Finds the first <button> element on the page -> Option AQuick Check:
findElement + tagName = first matching element [OK]
- Confusing findElement with findElements
- Using tagName but expecting multiple elements
- Mixing tagName with id or class selectors
Solution
Step 1: Check method usage
The methodfindElementrequires aBylocator with a string argument for tagName.Step 2: Validate syntax correctness
Only driver.findElement(By.tagName("input")); uses correct Java syntax with quotes around "input" and parentheses.Final Answer:
driver.findElement(By.tagName("input")); -> Option CQuick Check:
Correct method call with string tag name [OK]
- Missing quotes around tag name
- Using wrong brackets like [] or {}
- Omitting parentheses after findElement
<div> <h1>Title</h1> <h1>Subtitle</h1> </div>
What text will be printed by this Java Selenium code?
WebElement header = driver.findElement(By.tagName("h1"));
System.out.println(header.getText());Solution
Step 1: Understand findElement behavior
findElement returns the first matching element, here the first <h1> which contains "Title".Step 2: Check getText output
Calling getText() on the first <h1> returns its text content "Title" only.Final Answer:
Title -> Option BQuick Check:
findElement returns first tag's text [OK]
- Assuming it returns all matching elements
- Expecting concatenated text of all tags
- Confusing findElement with findElements
WebElement element = driver.findElement(By.tagName("button"));
System.out.println(element.getText());
Assuming the page has no <button> tags.
Solution
Step 1: Check element presence
Since no <button> tags exist, findElement cannot find any matching element.Step 2: Understand exception behavior
findElement throwsNoSuchElementExceptionif no element is found, causing runtime error.Final Answer:
It throws NoSuchElementException at runtime -> Option DQuick Check:
findElement throws error if no match [OK]
- Expecting null instead of exception
- Assuming empty string returned
- Confusing with findElements behavior
findElement(By.tagName()) and then clicks it?Solution
Step 1: Understand tagName limitations
By.tagName("input") finds the first <input> element regardless of type attribute.Step 2: Filter by type attribute manually
Check if the found element's type attribute equals "submit" before clicking.Step 3: Analyze options
WebElement submit = driver.findElement(By.tagName("input")); if ("submit".equals(submit.getAttribute("type"))) submit.click(); correctly finds first input, checks type, then clicks. WebElement submit = driver.findElement(By.tagName("input[type='submit']")); submit.click(); uses invalid tagName syntax. WebElement submit = driver.findElement(By.tagName("submit")); submit.click(); searches for non-existent tag <submit>. WebElement submit = driver.findElement(By.tagName("input")); submit.click(); clicks first input without type check.Final Answer:
WebElement submit = driver.findElement(By.tagName("input")); if ("submit".equals(submit.getAttribute("type"))) submit.click(); -> Option AQuick Check:
Use tagName then check attribute for type [OK]
- Trying to use CSS selector syntax inside tagName
- Assuming tagName can filter by attribute
- Clicking without verifying element type
Ready to prove it?
Pass the test and this pattern moves unknown
