0
0
Selenium Javatesting~15 mins

findElement by xpath in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Locate and verify the login button using XPath
Preconditions (3)
Step 1: Open the browser and navigate to 'https://example.com/login'
Step 2: Locate the login button using XPath '//button[@id="loginBtn"]'
Step 3: Verify that the login button is displayed on the page
✅ Expected Result: The login button is found using XPath and is visible on the page
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Assert that the login button element is displayed
Best Practices:
Use explicit waits to wait for the element to be present and visible
Use By.xpath locator with clear and maintainable XPath expressions
Close the browser after test execution
Automated Solution
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.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class FindElementByXPathTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com/login");

            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            WebElement loginButton = wait.until(
                ExpectedConditions.visibilityOfElementLocated(By.xpath("//button[@id='loginBtn']"))
            );

            assertTrue(loginButton.isDisplayed(), "Login button should be visible");

        } finally {
            driver.quit();
        }
    }
}

This code starts by setting up the Chrome WebDriver and opening the login page URL.

It uses an explicit wait to wait up to 10 seconds for the login button to be visible, locating it by the XPath expression //button[@id='loginBtn'].

Then it asserts that the button is displayed on the page, ensuring the element was found and is visible.

Finally, it closes the browser to clean up.

This approach avoids timing issues by waiting explicitly and uses a clear XPath locator for maintainability.

Common Mistakes - 3 Pitfalls
Using Thread.sleep() instead of explicit waits
Using a very long or complex XPath that is hard to maintain
Not closing the browser after the test
Bonus Challenge

Now add data-driven testing to locate and verify buttons with three different XPath expressions on the same page.

Show Hint