Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk7 min

How to Use Selenium with Java for Browser Automation

A practical Java Selenium guide: add the dependency, automate a browser, synchronize with dynamic pages, and decide when Selenium Grid makes sense.

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.

To use Selenium with Java, add the Selenium Java binding to a Maven or Gradle project, start a browser with WebDriver, locate elements, interact with them, wait for the page state your next action requires, and close the session with quit(). Selenium WebDriver controls browsers through their WebDriver implementations; Selenium describes WebDriver as a W3C Recommendation (Selenium WebDriver documentation).

This guide sets up a first script, shows how to make element selection and waits more reliable, and explains when to move from a local browser to Selenium Grid.

How Selenium with Java browser automation works

A Java Selenium test has three main parts: the Selenium Java library in your project, a browser such as Chrome, and the browser’s WebDriver implementation. Your Java code calls the WebDriver API; the browser and driver carry out those commands. You can run the browser locally or send commands to a remote Selenium Server.

Selenium Manager is the command-line tool Selenium bindings use by default to help manage browsers and drivers. That usually removes the need to download and configure a driver manually for a basic setup, but it does not remove the need for an installed or otherwise available browser. See Selenium’s Selenium Manager documentation for current behavior and details.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

How to set up Selenium WebDriver in Java

Add Selenium to a Maven project

Add the selenium-java dependency to your project’s pom.xml. Check Selenium’s downloads page for the current release rather than copying a version number from an older tutorial.

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

Replace CURRENT_SELENIUM_VERSION with the release currently listed by Selenium. The project must also use a Java version supported by that release; verify the current requirement on Selenium’s installation documentation rather than assuming an older JDK will work.

Use Gradle if that is your build tool

Selenium’s example project also demonstrates Gradle. Add the corresponding Selenium Java dependency to the project’s dependency block, using the current release listed on Selenium’s downloads page. Keep dependency versions managed in one place so upgrades are deliberate and repeatable.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Run a first Selenium Java script

This example follows Selenium’s documented sample form flow. It opens Chrome, fills in a field, submits the form, reads the result, and closes the browser even if a step throws an exception.

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.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");
            WebElement textBox = driver.findElement(By.name("my-text"));
            WebElement submitButton = driver.findElement(By.cssSelector("button"));
            textBox.sendKeys("Selenium");
            submitButton.click();
            String message = driver.findElement(By.id("message")).getText();
            System.out.println(message);
        } finally {
            driver.quit();
        }
    }
}
  • new ChromeDriver() starts a WebDriver session for Chrome.
  • get() navigates to the page.
  • By creates a locator, and findElement() looks up the matching element.
  • sendKeys() types into the text field; click() activates the submit button.
  • getText() reads the result, and quit() ends the browser session and releases its resources.

The example is a starting point, not a complete test: for automated verification, use your project’s test framework and assert an expected result instead of relying only on printed output. Selenium’s first-script guide documents the sample workflow.

Choose locators that survive page changes

Selenium supports locators including ID, name, class name, CSS selector, link text, and partial link text. Prefer an element’s stable ID or name when the application provides one. Use CSS when it clearly describes a stable element or relationship in the DOM. Avoid relying on positional selectors such as “the third button” unless position is genuinely part of the requirement: unrelated page changes can make them point to a different element.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Locator Good fit Watch for
By.id("submit") A stable, unique element ID. The ID must exist and be unique in the relevant document.
By.name("email") A form control with a stable name attribute. Names can repeat across a page.
By.cssSelector("button[type='submit']") A stable attribute or DOM relationship expressed clearly. Long chains tied to incidental layout are fragile.
By.linkText("Continue") A link whose visible text is distinctive and stable. Copy changes or duplicate link text can break or confuse lookup.

Selenium’s locator documentation describes the available strategies and their syntax.

How to wait for elements in Selenium

A navigation command reaching a page-load readiness state does not ensure that JavaScript-driven content is already visible or ready for interaction. Selenium calls this a common browser-automation challenge: the application must be in the state needed for the next command. Use an explicit wait for that state instead of guessing with a fixed pause.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement result = wait.until(
    ExpectedConditions.visibilityOfElementLocated(By.id("result")));
System.out.println(result.getText());

The ten-second timeout is an example, not a universal setting or performance target. Select a duration that fits the application and make the condition match what the next step needs: presence, visibility, clickability, or another documented expected condition. Explicit waits poll for the specified condition and proceed when it becomes true or fail when the timeout expires.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Selenium warns against mixing implicit and explicit waits because their interaction can create unpredictable timeout behavior. For predictable synchronization, choose an explicit-wait strategy for the conditions that matter and avoid adding a global implicit wait on top of it. See Selenium’s waiting strategies documentation.

Turn the script into a maintainable test

  • Move repeatable browser flows into your chosen Java test framework and assert observable outcomes.
  • Keep browser startup and teardown predictable; ensure sessions close even when an assertion or interaction fails.
  • Keep selectors and page-specific operations organized to reduce duplication and make changes easier to diagnose.
  • Wait for meaningful application states rather than assuming that a page is ready after navigation.

These practices improve maintainability, but they do not guarantee a particular test speed or reliability; those depend on the application, browser, environment, and test design.

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

When to run locally and when to use Selenium Grid

Execution option Best suited to Trade-off
Local WebDriver Learning Selenium, debugging, and runs where one available browser and machine are enough. Execution uses the machine and browser configuration available to the developer or local runner.
Selenium Grid Distributed execution across multiple machines, browsers, and operating systems. Grid adds remote infrastructure and configuration to manage.

Selenium documents Grid as its path for distributed execution. Choose it when browser or platform coverage, parallelized infrastructure, or execution across machines is a real project need; a local session is simpler for a first script. The Selenium documentation does not establish a universal performance or cost advantage for either approach. Start with the Selenium Grid documentation to understand its components and setup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Common Selenium Java problems and fixes

  • Browser or driver fails to start: confirm the browser is installed or otherwise available, that the installed versions are compatible, and that Selenium Manager can access what it needs. Check Selenium Manager’s current documentation for its management behavior and constraints.
  • NoSuchElementException: check that the locator matches the current DOM and that the element is in the active page or frame. If client-side rendering has not completed, wait for the relevant condition before looking it up.
  • TimeoutException while waiting: verify that the condition is correct, the target can become true in the current test state, and the locator is valid. Increasing the timeout alone will not fix a condition that can never be met.
  • Click or typing happens too early: wait for the specific state required for interaction, such as visibility or clickability, rather than inserting a fixed sleep.
  • Wait duration seems inconsistent: check whether the project combines implicit and explicit waits; Selenium warns that this can produce unpredictable results.
  • Browser processes remain after a run: put driver.quit() in a finally block or your test framework’s teardown so it runs after failures as well as successful tests.

Or skip the browser setup

If your goal is to capture a page rather than test browser interactions, ScreenshotNeo offers a website screenshot API and MCP server. One GET request can return an image or PDF; the API accepts capture options including full-page output, CSS selectors, viewport choices, and waits. See the ScreenshotNeo API documentation for parameters and response details.

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

ScreenshotNeo accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free plan to try 1,000 screenshots a month without a card.

Optional Java Selenium reference

For a book-length companion, the publisher lists Sujay Raghavendra’s Java Testing with Selenium: A Comprehensive Syntax Guide for Automation, published by Apress/Springer Nature in 2024. Its described coverage includes Java WebDriver setup, browser interactions, locators, waits, verification, and test organization. See the publisher’s book page for publication details.

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

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.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

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.