User Agents

Web browsers and everyday web tech, explained

Browser Automation with Java: Selenium & Playwright

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to automate a browser using Java with two popular libraries: Selenium and Playwright. You'll learn to write scripts that open a browser, navigate to pages, fill forms, click buttons, and extract data – all programmatically. This is useful for testing web applications, scraping data, or automating repetitive tasks. You'll need basic Java knowledge and a development environment set up.

What You'll Need

  • Java Development Kit (JDK) 8 or newer (Playwright requires Java 8+; Selenium works with Java 8+)
  • An IDE like IntelliJ IDEA, Eclipse, or VS Code with Java extensions
  • Maven or Gradle for dependency management (or manually download JAR files)
  • A modern web browser (Chrome, Firefox, or Edge) – Selenium and Playwright will use these
  • Basic understanding of HTML and CSS selectors (for locating elements)

Step-by-Step

  1. Set up a new Java project – Create a Maven project in your IDE. If using Maven, add the following dependencies to your pom.xml:
    <!-- Selenium -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.21.0</version>
    </dependency>
    
    <!-- Playwright -->
    <dependency>
        <groupId>com.microsoft.playwright</groupId>
        <artifactId>playwright</artifactId>
        <version>1.44.0</version>
    </dependency>
    If you prefer Gradle, add equivalent entries to build.gradle.
  2. Install browser drivers (Selenium only) – Selenium requires a driver executable for each browser. For Chrome, download ChromeDriver from the official site and place it on your PATH, or use Selenium Manager (built into Selenium 4.6+) which auto-downloads drivers. For Playwright, run npx playwright install in your project directory to download browser binaries (or use mvn exec:java with the Playwright CLI).
  3. Write a Selenium script – Create a Java class, e.g., SeleniumExample.java. Here's a basic script that opens Google, searches, and prints the title:
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.By;
    
    public class SeleniumExample {
        public static void main(String[] args) {
            WebDriver driver = new ChromeDriver();
            driver.get("https://www.google.com");
            driver.findElement(By.name("q")).sendKeys("Selenium");
            driver.findElement(By.name("q")).submit();
            System.out.println("Page title: " + driver.getTitle());
            driver.quit();
        }
    }
    Run it. If you get a driver error, ensure the driver is in PATH or set the system property: System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");.
  4. Write a Playwright script – Create another class, e.g., PlaywrightExample.java . Playwright's API is different – you use a Browser and Page object: import com.microsoft.playwright.*; public class PlaywrightExample { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { Browser browser = playwright.chromium().launch(); Page page = browser.newPage(); page.navigate("https://www.google.com"); page.waitForLoadState(); System.out.println("Page title: " + page.title()); browser.close(); } } } Run it. Playwright automatically downloads browsers on first run if you used the CLI, but you can also call playwright.chromium().launch() which uses the installed browser.
  5. Locate elements reliably – Both libraries support multiple selectors. Selenium uses By.id, By.className, By.cssSelector, By.xpath. Playwright uses page.locator() with CSS or XPath, and also provides role-based selectors like getByRole('button'). Prefer IDs and CSS classes over XPath when possible.
  6. Handle waits and synchronization – Web pages load asynchronously. Selenium: use WebDriverWait with ExpectedConditions. Playwright: use page.waitForSelector() or auto-waiting actions (like click() which waits for actionability). Example for Selenium:
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("result")));
    For Playwright, simply call page.click("#result") – it waits automatically.
  7. Interact with forms and buttons – Both libraries allow typing, clicking, selecting dropdowns, and checking checkboxes. Selenium: sendKeys(), click(), Select class. Playwright: fill(), click(), selectOption().
  8. Take screenshots and extract data – For debugging or recording, take screenshots. Selenium: File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);. Playwright: page.screenshot(new Page.ScreenshotOptions().setPath("screenshot.png")). To extract text, use element.getText() (Selenium) or locator.textContent() (Playwright).
  9. Run in headless mode – For CI or background tasks, run without a visible browser. Selenium: ChromeOptions options = new ChromeOptions(); options.addArguments("--headless");. Playwright: playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true)).
  10. Manage multiple tabs and windows – Selenium: use driver.getWindowHandles(). Playwright: page.waitForPopup() or browser.newPage().
  11. Clean up resources – Always close the browser and driver in a finally block or try-with-resources (as shown in Playwright example) to avoid memory leaks.

Common Mistakes

  • Forgetting to add the driver to PATH – leads to IllegalStateException in Selenium.
  • Using incorrect selectors – copy-pasting from DevTools without verifying uniqueness.
  • Not waiting for elements – causes NoSuchElementException or flaky tests.
  • Mixing up Selenium and Playwright APIs – they are different; don't try to use Selenium's findElement in Playwright.
  • Not closing the browser – leaves zombie processes.
  • Hard-coding absolute paths – use relative paths or system properties.

Tips

  • Use Playwright's codegen tool (npx playwright codegen) to generate starter scripts by recording your actions.
  • Use Selenium's Page Object Model to keep tests maintainable.
  • Use explicit waits over implicit waits in Selenium for better control.
  • Prefer CSS selectors over XPath for readability and speed.
  • Run tests in parallel using TestNG or JUnit for faster execution.
  • Keep your browser and driver versions in sync – mismatches cause errors.

Troubleshooting

  • Driver executable not found – Download the correct driver for your browser version and set the system property, or use Selenium Manager (Selenium 4.6+).
  • Element not found – Check if the element is inside an iframe. Selenium: switch to iframe using driver.switchTo().frame(). Playwright: use frameLocator(). Also ensure the page has fully loaded – add waits.
  • StaleElementReferenceException – The DOM changed after locating the element. Re-locate the element or use a fresh reference.
  • Playwright browser not launching – Run npx playwright install to download browser binaries. If you're behind a firewall, you may need to set proxy environment variables.
  • Timeouts – Increase default timeouts or use longer waits for slow pages. Playwright: page.setDefaultTimeout(30000).
  • Headless mode issues – Some sites block headless browsers. You can use headful mode for debugging, or add user-agent strings.

Frequently Asked Questions

Which library is better, Selenium or Playwright?

Playwright is newer, faster, and has a more modern API with auto-waiting and better debugging. Selenium is more established and supports more browsers and languages. Choose based on your project's needs and team familiarity.

Can I use both in the same project?

Yes, you can include both dependencies, but they are separate frameworks. Mixing them in one test is usually not recommended because of conflicting concepts, but you can use them in different test classes.

Do I need to install a browser separately?

For Selenium, you need a browser installed (like Chrome) plus its driver. For Playwright, you can install its own browser binaries via npx playwright install, which are isolated from your system browsers.

How do I handle file downloads?

Selenium: set browser preferences to download to a specific directory. Playwright: use page.waitForEvent('download') and then download.saveAs().

Can I run scripts on a remote server?

Yes, both support remote execution. Selenium uses Selenium Grid; Playwright has its own remote server. You can also use cloud services like BrowserStack or Sauce Labs (though not covered here).

What about authentication pop-ups?

Selenium: use Alert interface or pass credentials in URL (e.g., http://user:pass@site.com). Playwright: use page.authenticate() or handle the dialog via page.on('dialog').