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

To use Selenium with Java, add Selenium’s Java binding to your project, start a browser with WebDriver, navigate to a page, locate elements, interact with them, and close the session. For dynamic pages, wait for the specific state your next action needs rather than relying on fixed delays. This guide walks through a local Chrome example, maintainable locators, explicit waits, troubleshooting, and when to consider distributed execution.

What Selenium WebDriver does

Selenium WebDriver is an API and protocol for controlling browsers. Selenium describes WebDriver as a W3C Recommendation and says it “drives a browser natively” (Selenium WebDriver documentation). In Java, your code uses Selenium’s Java binding to send commands to a browser’s WebDriver implementation. Those commands can run against a browser on the same machine or through Selenium Server.

A basic local setup has three parts: your Java project and Selenium library, an installed or otherwise available browser, and the browser’s WebDriver implementation. Selenium Manager is used by Selenium bindings by default to automate browser and driver management, so a basic setup generally does not require manually downloading a driver. It does not remove the need for an available browser. Check Selenium’s current installation and downloads pages for release and compatibility details before updating a project.

How to set up Selenium WebDriver in Java

Add the Java dependency

For Maven, the dependency coordinates are org.seleniumhq.selenium:selenium-java. Add that artifact to your pom.xml and set its version to a current release listed on Selenium’s downloads page; do not copy an old version from a tutorial without checking. Selenium’s getting-started documentation also demonstrates project setup with Gradle. Check the current official installation guidance for the supported Java baseline rather than assuming a requirement from an older example.

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.
#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.

Run a first browser script

The following Java program uses Selenium’s documented sample web form. It opens Chrome, enters text, submits the form, prints the result, and closes the session even if an operation fails. Add the dependency above and ensure a Chrome browser is available before running it.

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();
        }
    }
}
  • driver.get(url) navigates to the page.
  • By creates a locator; findElement returns the matching element.
  • sendKeys enters text and click activates the button.
  • getText reads the result, and quit ends the browser session and closes its windows.

This is an illustrative adaptation of Selenium’s first-script example, not a report of a separately executed test. The official example uses the same sample form and demonstrates navigation, locating, input, submission, result lookup, and cleanup (First script).

Choose locators that survive page changes

Selenium supports locator strategies including ID, name, class name, CSS selector, link text, and partial link text. The appropriate choice depends on the page’s DOM and the application’s conventions (Selenium locator documentation).

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.
Locator Useful when Maintenance consideration
By.id("submit") The intended element has a unique, stable ID. Usually clear to read; confirm the application keeps the ID stable.
By.name("email") A form field has a meaningful, stable name. Good for form controls when names are not duplicated or frequently changed.
By.cssSelector("button[type='submit']") A stable attribute or relationship identifies the target. Keep the selector specific enough to identify intent without depending on incidental DOM structure.
By.className("primary") A useful class identifies the element. Classes may be shared for styling, so verify that the locator selects the intended element.
By.linkText("Continue") A link’s visible text is a suitable identifier. Text changes, localization, or duplicate links can make this brittle.

Prefer a stable ID or name when the application provides one. Use CSS where it expresses a stable attribute or relationship. Avoid relying on positional assumptions such as “the third button” unless order itself is the behavior being tested.

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

How to wait for elements in Selenium

A navigation command reaching its load readiness state does not guarantee that JavaScript-driven content is present or visible. Selenium calls waiting for the application to reach a state required by the next command one of the most common browser-automation challenges (Waiting strategies).

Use an explicit wait for the required condition

For example, wait until a result element becomes visible before reading it. The ten-second duration here is illustrative, not a universal timeout recommendation.

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.
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());

Choose a condition that describes what the next operation needs: for example, visibility before reading text, or clickability before clicking. Explicit waits poll for their specified condition and proceed when it is met or time out if it is not. A longer timeout does not fix a wrong locator or a page that never reaches the expected state.

Do not mix implicit and explicit waits

Selenium warns that combining implicit and explicit waits can produce unpredictable timeout behavior. For a project that uses explicit, condition-specific waits, avoid setting an implicit wait as a second timing mechanism. Keep synchronization tied to observable page conditions instead of adding arbitrary sleeps.

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

Turn the script into a repeatable test

A one-off script shows the mechanics; a useful test also checks an outcome. Move repeatable workflows into the test framework already used by the project, assert an observable result, and make setup and teardown predictable. Keep page-specific selectors and interactions organized so a changed control does not require editing the same locator throughout the test suite.

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

Run the local script first to distinguish application and test problems from remote infrastructure problems. When coverage must extend across machines, browsers, or operating systems, Selenium Grid is Selenium’s documented route to distributed execution. Grid adds setup and operational considerations in exchange for broader execution environments; it is most relevant when local runs no longer meet the project’s coverage or scaling needs (Selenium Grid documentation).

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

Troubleshooting common failures

Browser or driver startup fails

Confirm that the target browser is installed or otherwise available and that the project uses Selenium’s current setup guidance. Selenium Manager handles browser and driver management by default through Selenium bindings, but it cannot supply a browser that is unavailable in the environment. Check the exception details and the current Selenium installation guidance before adding a manual driver download step.

NoSuchElementException appears

The locator may not match the current DOM, the page may not yet contain the element, or the script may be looking at the wrong page state. Verify the locator against the page, then wait for the required condition if the content appears asynchronously. Do not mask a bad locator by increasing timeouts indefinitely.

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.

An element is found but is not ready for interaction

Finding an element is not the same as proving that it is visible or ready for the next action. Wait for the condition relevant to the operation, such as visibility or clickability, and check whether an overlay or page transition is affecting the target.

A test passes locally but fails in another environment

Compare the browser, operating system, and page state used by each run. Selenium Grid is designed to execute across browser and platform combinations; distribute only after the test’s locators, assertions, and waits behave predictably in the local environment.

Or skip the browser setup

If the task is to save a page image or PDF rather than interact with a workflow or verify application behavior, ScreenshotNeo is a screenshot API and MCP server, not a substitute for Selenium tests. One GET request can return an image or PDF. For example, this cURL request captures a page as WebP; see the API documentation for response formats and options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://www.selenium.dev/selenium/web/web-form.html -o shot.webp

ScreenshotNeo accepts cookie or consent banners like 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 the response identifies the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

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

Sign up for ScreenshotNeo’s free plan to try screenshot capture without a card.

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.