October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
browser automation

How to Automate a Browser with Java: Selenium and Playwright Guide

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To automate a browser with Java, add a browser-automation library to a Maven or Gradle project, create a browser session, open a URL, locate an element, perform an action, and always close the session. Selenium WebDriver is the standard-oriented choice; Playwright is an alternative that manages version-matched Chromium, WebKit and Firefox binaries. This guide shows both workflows, explains browser setup, and covers local, CI and remote execution.

What you need before writing Java browser automation

  • A supported JDK: use a Java version supported by the current Selenium or Playwright release. Check the live project documentation because minimum versions change.
  • Maven or Gradle: dependencies and transitive libraries should come from your build tool rather than manually copied JAR files.
  • A browser runtime: Selenium uses a browser and its WebDriver implementation; Playwright installs browser binaries through its CLI.
  • A repeatable test or application entry point: run the code from a JUnit test, a main class, or a CI job.

Selenium’s setup guidance describes the three moving parts as the language library, browser and driver. Start with its getting-started documentation and Java library installation page for current compatibility details.

Automate Chrome with Selenium WebDriver

1. Add the Selenium Java dependency

For Maven, add the official artifact below. Do not permanently copy an old version from a blog post; select the current version shown in Selenium’s documentation or repository.

<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>CURRENT_VERSION</version>
</dependency>

With Gradle, use the equivalent declaration:

dependencies {
    implementation("org.seleniumhq.selenium:selenium-java:CURRENT_VERSION")
}

2. Write a complete first script

The following example follows Selenium’s documented sequence: create a WebDriver, navigate with get, find an element, interact with it, and close the session in finally. The CSS selector targets the search box on Selenium’s own site; replace it when automating another page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserExample {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://www.selenium.dev/");
            WebElement heading = driver.findElement(By.tagName("h1"));
            System.out.println("Page heading: " + heading.getText());
        } finally {
            driver.quit();
        }
    }
}

quit() ends the complete browser session. Prefer it over leaving a window open or calling only close(), which closes one window and can leave the driver process running.

3. Locate and interact with elements

Use the most stable locator available. Selenium supports ID, name, tag name, class name, CSS selectors and XPath.

driver.findElement(By.id("email")).sendKeys("[email protected]");
driver.findElement(By.cssSelector("button[type='submit']")).click();
String title = driver.getTitle();

For dynamic pages, wait for a condition instead of inserting arbitrary sleeps:

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(15));
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(
    By.cssSelector("button[type='submit']")));
button.click();

4. Run headless in CI

Graphical desktops are often unavailable in continuous integration. Configure Chrome options before creating the driver:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import org.openqa.selenium.chrome.ChromeOptions;

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new", "--window-size=1440,1000");
WebDriver driver = new ChromeDriver(options);

Choose a window size deliberately: responsive layouts can expose different elements at different widths. Keep screenshots, logs and the failing URL as CI artifacts.

Browser and driver setup with Selenium

Selenium WebDriver uses browser-specific implementations while exposing a common API. Your machine or CI image must have a compatible browser and driver arrangement. When a session fails before the first page loads, check the browser version, driver availability, executable permissions and the current Selenium installation instructions. Selenium documents WebDriver as a W3C Recommendation and describes WebDriver as driving a browser natively at its WebDriver documentation.

For multiple machines or parallel execution, Selenium Grid is the documented route to remote and scaled execution. A local run and a Grid run use the same high-level WebDriver model, but the remote endpoint, browser capabilities and infrastructure become part of your configuration.

Playwright for Java: a different setup model

Add the Maven module

Playwright for Java is distributed through Maven. Follow the current Java installation guide for the dependency version rather than pinning an obsolete example.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>CURRENT_VERSION</version>
</dependency>

Install matching browser binaries

Playwright’s documented workflow includes a CLI step that installs browser binaries associated with the selected Playwright release. Consult the browser installation page for the command appropriate to your build and operating system. Repeat the installation when you upgrade Playwright if the release requires new binaries.

Run a first Playwright script

import com.microsoft.playwright.*;

public class PlaywrightExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(
                new BrowserType.LaunchOptions().setHeadless(true));
            Page page = browser.newPage();
            page.navigate("https://www.selenium.dev/");
            System.out.println(page.locator("h1").innerText());
            browser.close();
        }
    }
}

Playwright also provides firefox() and webkit() browser types. Its browser binaries are version-managed rather than relying solely on a separately maintained driver executable.

Selenium or Playwright?

Decision factor Selenium Playwright
Browser strategy WebDriver implementations and installed browser/driver compatibility Playwright-managed, version-matched browser binaries
Java setup org.seleniumhq.selenium:selenium-java through Maven or Gradle Playwright Maven module plus CLI browser installation
Browser coverage Depends on available WebDriver implementations and browsers Chromium, WebKit and Firefox through Playwright APIs
Remote scale Selenium documents Grid for remote and scaled execution Choose the Playwright runner and infrastructure that fit your CI or remote platform
Best fit Teams requiring the WebDriver standard, established Grid workflows or existing Selenium knowledge Projects that value Playwright’s browser-version workflow and its Chromium, WebKit and Firefox coverage

Neither project’s documentation supplies a controlled performance benchmark here, so do not select one on an assumed universal speed or reliability advantage. Compare the browsers you must support, how your CI images are maintained, whether Grid is required, and the team’s existing skills.

Reliable automation patterns

Use explicit readiness conditions

Wait for visibility, clickability, a URL change or a specific page state. Avoid long fixed sleeps: they slow successful runs and still fail when a page takes longer than expected.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Isolate sessions

Create a fresh browser context or driver for independent tests. Clear cookies and storage when state must not leak between cases. Supply test credentials through CI secrets, never source code.

Control nondeterminism

Pin dependency versions in a lockfile or build configuration, record browser versions in CI logs, and keep test data stable. Use a dedicated test environment when production content changes frequently.

Capture diagnostics

On failure, record the exception, current URL, page title, browser console output where available and a screenshot. Preserve these files as build artifacts so a headless failure can be investigated.

Troubleshooting common failures

“Unable to obtain driver” or session creation errors

Verify that the browser is installed, the driver arrangement matches it, and the process can execute the driver. Recheck Selenium’s current setup page after browser updates.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Playwright reports missing executables

Run the browser-install command documented for your exact Playwright version. A dependency upgrade can require a fresh binary download.

Element cannot be found

Confirm the locator against the live DOM, wait for the page state that creates the element, and check whether it is inside an iframe or shadow DOM. Switch to a stable data attribute when you control the application.

Click is intercepted or times out

Wait for the element to be clickable, scroll it into view, dismiss an actual overlay, and verify that the viewport is large enough. Do not force a JavaScript click unless bypassing the real user interaction is intentional.

Works locally but fails in CI

Compare browser and Java versions, run with an explicit headless window size, install required browser dependencies in the CI image, and save screenshots and logs from the failing job.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Tests are flaky after navigation

Wait on a meaningful application condition rather than a generic delay, avoid sharing mutable accounts between parallel jobs, and make cleanup run even when assertions fail.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean website image or PDF rather than an interactive test, ScreenshotNeo provides a single HTTP request and an MCP server for AI agents. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits cost nothing; response headers identify the page verdict and whether the shot was billed.

Use the API documentation at screenshotneo.com/docs/ for all options. A cURL capture looks like this:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The same request in Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

And Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo includes full-page and element captures, dark mode, device presets, retina scale, custom CSS and JavaScript, click and wait actions, request blocking, headers and cookies, timezone and geolocation, transparent backgrounds, resizing, configurable caching, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, PDF controls, a usage API and an OpenAPI specification. Its MCP tools are take_screenshot, get_page_info and capture_pdf, so Claude, Cursor and other MCP clients can request captures.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing gives two months free. Create a free ScreenshotNeo account to start.

FAQ

Does Selenium require writing a driver executable path?

That depends on your Selenium and environment setup. Follow the current official installation guidance and verify browser-driver compatibility before hard-coding paths.

Can Java automation run without a visible desktop?

Yes. Configure a supported headless mode, provide a deliberate viewport, and install the browser dependencies required by your CI image.

Should I use Selenium and Playwright in the same project?

Usually choose one for a given test suite. Mixing can be justified during migration or when separate components have different infrastructure requirements, but it increases dependency and diagnostic complexity.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can Selenium automate browsers other than Chrome?

Yes. Selenium exposes browser-specific WebDriver implementations; configure the browser and implementation your environment supports.

Do Playwright browser binaries update with the Maven dependency?

The Java library and browser binaries are version-related but installed separately through the documented CLI workflow, so rerun browser installation when an upgrade requires it.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.