Testing Tools

Selenium WebDriver Tutorial with Java: Complete 2026 Guide

Learn Selenium WebDriver with Java step by step — Maven setup, your first script, locators, explicit waits, TestNG assertions and the Page Object Model.

✍️ By QA Jobs India📅 10 Oct 2026⏱ 7 min read

Selenium WebDriver is still one of the most requested automation skills in Indian QA job descriptions, and Java is the language most teams pair it with. This Selenium WebDriver tutorial walks you through everything a beginner needs: project setup, your first script, locators, waits, TestNG and the Page Object Model.

Every code sample uses Selenium 4 and runs against a practice form hosted on the official Selenium website, so you can copy, run and experiment without setting up your own application.

Key takeaways

  • Selenium 4 includes Selenium Manager, which downloads the right browser driver automatically.
  • Prefer id, name and CSS selectors; use XPath when you need text or complex relationships.
  • Use explicit waits instead of Thread.sleep for reliable tests.
  • Structure real projects with TestNG and the Page Object Model.

What is Selenium WebDriver?

Selenium WebDriver is an open-source library that controls real browsers — Chrome, Firefox, Edge and Safari — through a standard W3C protocol. Your test code sends commands such as “open this URL”, “click this button” or “read this text”, and the browser driver executes them. It supports Java, Python, C#, JavaScript and Ruby; this guide uses Java.

Step 1: Set up the project

Install JDK 11 or later (17 or 21 is a good choice), an IDE such as IntelliJ IDEA Community or Eclipse, and Google Chrome. Create a new Maven project and add Selenium and TestNG to pom.xml:

<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.25.0</version> <!-- use the latest 4.x from Maven Central -->
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.10.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

You do not need to download ChromeDriver manually or add WebDriverManager. Since Selenium 4.6, Selenium Manager finds or downloads a matching driver for your installed browser automatically.

Step 2: Write your first script

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FirstScript {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://www.selenium.dev/selenium/web/web-form.html");
            System.out.println("Title: " + driver.getTitle()); // Web form

            WebElement textBox = driver.findElement(By.name("my-text"));
            WebElement submitButton = driver.findElement(By.cssSelector("button"));

            textBox.sendKeys("Selenium");
            submitButton.click();

            WebElement message = driver.findElement(By.id("message"));
            System.out.println(message.getText()); // Received!
        } finally {
            driver.quit();
        }
    }
}

Run it and Chrome opens, fills the form, submits it and closes. The finally block with driver.quit() ensures the browser closes even if a step fails — a habit worth keeping in every test.

Step 3: Master locators

Locators tell Selenium which element to interact with. Choosing stable locators is the biggest factor in test reliability.

LocatorExampleWhen to use
By.idBy.id(“message”)First choice when a unique id exists
By.nameBy.name(“my-text”)Form fields
By.cssSelectorBy.cssSelector(“input[type=’password’]”)Fast, flexible, readable
By.xpathBy.xpath(“//button[text()=’Submit’]”)Text matching, parent/sibling navigation
By.linkTextBy.linkText(“Return to index”)Links with exact visible text
By.className / By.tagNameBy.className(“form-control”)Usually combined with other strategies

Avoid absolute XPaths such as /html/body/div[2]/form/input — they break with the smallest layout change. If developers can add dedicated attributes like data-testid, use them with CSS selectors.

Step 4: Use explicit waits

Modern web pages load content dynamically, so an element may not exist yet when your code looks for it. Thread.sleep wastes time and still fails on slow days. Use WebDriverWait to wait only as long as needed:

import java.time.Duration;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement message = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("message")));

Common conditions include elementToBeClickable, visibilityOfElementLocated, textToBePresentInElementLocated and urlContains. The Selenium documentation advises against mixing implicit and explicit waits, because it can cause unpredictable wait times.

Step 5: Convert it into a TestNG test

A main method is fine for learning, but real tests need setup, teardown, assertions and reports. TestNG provides all of these:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class WebFormTest {
    private WebDriver driver;

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

    @Test
    public void submitFormShowsConfirmation() {
        WebFormPage page = new WebFormPage(driver);
        page.open();
        page.submitText("QA Jobs India");
        Assert.assertEquals(page.getMessage(), "Received!");
    }

    @AfterMethod
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

Step 6: Apply the Page Object Model

The Page Object Model (POM) keeps locators and page actions in one class per page, so tests read like business steps and a UI change is fixed in one place. Here is the page class used by the test above:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class WebFormPage {
    private final WebDriver driver;
    private final By textInput = By.name("my-text");
    private final By submitButton = By.cssSelector("button");
    private final By message = By.id("message");

    public WebFormPage(WebDriver driver) {
        this.driver = driver;
    }

    public void open() {
        driver.get("https://www.selenium.dev/selenium/web/web-form.html");
    }

    public void submitText(String text) {
        driver.findElement(textInput).sendKeys(text);
        driver.findElement(submitButton).click();
    }

    public String getMessage() {
        return driver.findElement(message).getText();
    }
}

Notice that the test class never mentions a locator. If the submit button’s markup changes, you update one line in WebFormPage and every test that uses it keeps working. In larger projects, add a BasePage class for shared helpers such as waits and clicks, and keep test data in separate files.

Step 7: Handle dropdowns, alerts, frames and windows

Real applications go beyond text boxes and buttons. These four situations appear in almost every project and in many interviews, so practise each one on the same web form page or another demo site:

// Dropdown (HTML select element)
import org.openqa.selenium.support.ui.Select;
Select dropdown = new Select(driver.findElement(By.name("my-select")));
dropdown.selectByVisibleText("Two");

// JavaScript alert
driver.switchTo().alert().accept();      // or .dismiss()

// iframe
driver.switchTo().frame("frameNameOrId");
// ... interact inside the frame ...
driver.switchTo().defaultContent();

// New tab or window
String original = driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(original)) {
        driver.switchTo().window(handle);
    }
}

The Select class works only with native select elements; custom dropdowns built from div elements are handled with normal clicks. When an element is inside an iframe, Selenium cannot see it until you switch into that frame, which is a common cause of NoSuchElementException for beginners. Remember to switch back to the main page or original window when you are done.

Taking a screenshot is also useful while debugging. Cast the driver to TakesScreenshot and call getScreenshotAs(OutputType.FILE), then copy the file into a screenshots folder. Most frameworks capture a screenshot automatically whenever a test fails, which makes failures in CI much easier to investigate. With these extra skills, the examples in this Selenium WebDriver tutorial cover the core of what interviewers expect from a junior automation engineer.

Common beginner mistakes

  • Using Thread.sleep everywhere instead of explicit waits.
  • Copying long, auto-generated XPaths from browser tools.
  • Forgetting driver.quit(), which leaves browser processes running.
  • Writing tests that depend on each other’s order or data.
  • Automating everything — unstable or one-off features are often better tested manually.

What to learn after this Selenium WebDriver tutorial

  • Handling dropdowns (Select class), alerts, frames and multiple windows.
  • Data-driven tests with TestNG @DataProvider.
  • Headless runs and parallel execution, and Selenium Grid for cross-browser testing.
  • Reports (Allure or Extent), screenshots on failure, and running the suite in Jenkins or GitHub Actions.

The official Selenium WebDriver documentation covers each of these with examples. For the bigger picture of what to learn and in which order, see our software testing roadmap. Once your framework is on GitHub, add it to your resume as shown in our QA resume for freshers guide.

🚀 Looking for Selenium automation jobs?

QA Jobs India shares 100+ fresh QA & software testing openings every morning — manual, automation, API and remote roles.

See today’s QA jobs →

FAQs

Do I need to download ChromeDriver?

No. With Selenium 4.6 and later, Selenium Manager handles drivers automatically for Chrome, Firefox and Edge.

How much Java do I need for Selenium?

Core Java: classes and objects, methods, conditions, loops, collections, exceptions and basic inheritance is enough to start.

Is Selenium still relevant in 2026?

Yes. Playwright is growing fast, but Selenium remains widely used in Indian companies and appears in a large share of automation job postings.

TestNG or JUnit?

Both work. TestNG is very common in Indian QA teams for its grouping, parallel runs and data providers; JUnit 5 is equally capable.

How long does it take to learn Selenium?

With an hour or two of daily practice, most learners build a basic POM framework in six to ten weeks.

Conclusion

This Selenium WebDriver tutorial gave you a working Java setup, reliable locators, explicit waits, TestNG tests and a Page Object Model structure — the foundation of every Selenium framework. Practise on a few demo sites, push your framework to GitHub, and then explore the daily QA jobs list for automation roles that match your new skills.

💎 Get every QA opening, every day

Join QA Jobs India Premium for 100+ verified QA jobs daily with HR contact details.

✓ You're subscribed — job alerts arrive daily at 9 AM
Scroll to Top