This guide walks you through setting up and using Selenium WebDriver with Java to automate browser actions like clicking, typing, and extracting data from web pages. You’ll learn how to write a simple test script that opens a browser, interacts with elements, and verifies results. No prior Selenium experience is needed, but basic Java and Maven knowledge helps.
What You’ll Need
- Java Development Kit (JDK) – version 8 or later (11 or 17 recommended). Check with
java -version. - Maven – for dependency management (or Gradle if you prefer).
- An IDE – IntelliJ IDEA, Eclipse, or VS Code with Java extensions.
- A modern browser – Chrome, Firefox, or Edge.
- WebDriver binaries – Selenium Manager (in Selenium 4.6+) handles this automatically, so you don’t need to download them manually.
Step-by-Step
- Create a Maven project – In your IDE, create a new Maven project with a
pom.xmlfile. - Add Selenium dependency – In
pom.xml, add the Selenium Java dependency (version 4.x). Example:<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.21.0</version> </dependency>Save and let Maven download the libraries.
- Write your first script – Create a Java class (e.g.,
FirstTest.java) with amainmethod. Start with the essential imports:import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver;
- Instantiate the driver – Inside
main, create a ChromeDriver instance:WebDriver driver = new ChromeDriver();
Selenium Manager will automatically find and launch the correct ChromeDriver binary.
- Navigate to a URL – Use
driver.get("https://example.com")to open a page. - Locate elements – Use
driver.findElement(By.id("someId"))or other By strategies (className, xpath, cssSelector, name, linkText). For example, to find a search box by name:WebElement searchBox = driver.findElement(By.name("q")); - Interact with elements – Type text with
searchBox.sendKeys("Selenium"), click with.click(), or clear with.clear(). - Wait for elements – Use explicit waits to avoid flaky tests:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement result = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("result"))); - Extract data – Get text with
element.getText()or attributes withelement.getAttribute("value"). - Close the browser – Always call
driver.quit()in afinallyblock to clean up resources. - Run the script – Right-click and run the class. You should see the browser open, perform actions, and close.
Common Mistakes
- Not using waits – Trying to interact with elements before they are ready causes
NoSuchElementException. Always use explicit waits. - Hardcoding sleeps –
Thread.sleep(5000)is unreliable and slows tests. Use WebDriverWait instead. - Forgetting to quit – Leaving browsers open consumes memory. Use
driver.quit()in a finally block. - Using wrong locators – Fragile locators like absolute XPath break easily. Prefer IDs, names, or CSS selectors.
- Ignoring browser versions – If Selenium Manager fails, you may need to manually download the matching driver and set the system property.
Tips
- Use Page Object Model – For larger projects, separate page-specific locators and methods into classes to keep tests maintainable.
- Run headless – For CI/CD, set
ChromeOptions options = new ChromeOptions(); options.addArguments("--headless");to run without a UI. - Take screenshots – On failure, capture a screenshot with
((TakesScreenshot)driver).getScreenshotAs(...)for debugging. - Use relative locators – Selenium 4 offers
withTagName(),above(),below()to find elements relative to others. - Keep selectors simple – Prefer IDs and data attributes over complex XPath.
Troubleshooting
- Browser doesn’t open – Ensure the browser is installed and the driver matches the browser version. Selenium Manager should handle this, but if not, download the driver manually and set
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"). - NoSuchElementException – The element isn’t present yet or the locator is wrong. Add an explicit wait and double-check the locator in DevTools.
- ElementNotInteractableException – The element is present but hidden or disabled. Wait for it to be clickable, or scroll into view with
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element). - StaleElementReferenceException – The page changed after you found the element. Re-find the element after the change.
- TimeoutException – The wait condition never became true. Increase the timeout or check that the condition is correct.
- WebDriverManager errors – If Selenium Manager fails due to network, manually download the driver and set the system property.
Frequently Asked Questions
Can I use Selenium with Java for web scraping?
Yes, but be respectful of a site’s terms of service and robots.txt. Selenium is heavier than dedicated scraping tools, but it can handle JavaScript-heavy pages.
How do I handle pop-ups and alerts?
Use driver.switchTo().alert().accept() to accept or .dismiss() to cancel. For JavaScript pop-ups, switch to the alert before interacting.
What is the difference between findElement and findElements?
findElement returns the first matching element (or throws if none). findElements returns a list of all matches, which can be empty.
How do I handle iframes?
Switch to the frame first: driver.switchTo().frame("frameName") or by index. After interacting, switch back with driver.switchTo().defaultContent().
Is Selenium still the best choice for browser automation?
It’s the most widely used and well-documented. Alternatives like Playwright and Cypress are faster for some cases, but Selenium supports many languages and browsers.
How do I run tests in parallel?
Use TestNG or JUnit with Selenium Grid. Each test thread gets its own WebDriver instance, and you can configure parallel execution in your test framework.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Stop Chrome Auto-Opening on Windows Startup
- Snapchat Security: 12 Tips to Lock Down Your Account
- Missing Comma on iPhone Keyboard: Fix & Where It Went
- Get Pixel Weather & Screenshot Apps on Any Android
- Other Storage on Android: What It Is & How to Clean It
- Facebook Messenger Games: How to Play With Friends