Meet 2025’s Top-rated Software Test Management Tool. Learn More >

Getting Started with Selenium Java WebDriver: A Step-by-Step Guide

Selenium Java WebDriver

In this article

Selenium Java WebDriver: A Step-by-Step Guide

Selenium WebDriver, one of the most powerful tools for automating web browsers, has become an indispensable asset for testers and developers in ensuring the functionality and performance of web applications. Java, being a widely-used programming language, provides an excellent foundation for leveraging Selenium WebDriver to perform automated testing effectively. In this step-by-step guide, we’ll walk you through the process of getting started with Selenium WebDriver using Java.

Streamline QA with QA touch

Step 1: Set Up Your Development Environment

  •  Before diving into Selenium WebDriver, ensure you have the following prerequisites installed:
  •  Java Development Kit (JDK): Download and install the latest version of JDK compatible with your operating system from the official website Java Downloads | Oracle
  • Now, set the path of the bin directory in environment variables, Open environment variables(from control panel) locate path and add the JDK location in the path and save changes. Use the “ java – version” command in the command prompt to verify the java installation.
  •  Integrated Development Environment (IDE): Choose an IDE such as Eclipse or IntelliJ IDEA and install it.
  •  Selenium WebDriver: Download the Selenium WebDriver Java bindings from the official Selenium website or include it as a dependency in your project using tools like Maven or Gradle.

Related: Best Practices For Dealing With Dynamic Web Elements In Selenium

Step 2: Create a New Java Project

  • Launch your preferred IDE and create a new Java project. Configure the project settings and ensure you’ve added the Selenium WebDriver library to your project’s classpath.

Step 3: Write Your First Selenium WebDriver Test

  • Let’s create a simple test that opens a web browser, navigates to a webpage, and verifies its title.
  • Selenium supports 5 popular web browsers like Google chrome, Mozilla Firefox, Microsoft Edge, Safari and Opera.
  • Replace “path/to/chromedriver” with the actual path to your ChromeDriver executable file.

Example Code (Chrome browser):

java

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

public class MyFirstTest {

 public static void main(String[] args) {

 // Set the path to the ChromeDriver executable

 System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);

 // Initialize ChromeDriver

 WebDriver driver = new ChromeDriver();

 // Navigate to a website

 driver.get(“https://www.example.com”);

 // Get and print the title of the webpage

 String pageTitle = driver.getTitle();

 System.out.println(“Page Title: ” + pageTitle);

 // Close the browser

 driver.quit();

 }

}

Step 4: Run Your Selenium Test

Execute the test you’ve created within your IDE. It will launch a Chrome browser, navigate to the specified URL, retrieve the title of the webpage, and display it in the console.

Related Read: A Step-By-Step Guide On How To Integrate Jenkins With Selenium

Step 5: Explore Selenium Features and Functions

Selenium WebDriver offers a rich set of functionalities to interact with web elements, handle different browser actions, perform assertions, and more. Here are some essential concepts to explore further:

  • Locating Elements: Use methods like findElement and findElements to locate elements on a webpage using various selectors (ID, class name, XPath, etc.).

ID: This locator targets elements by their unique HTML id attribute.

  •             driver.findElement(By.id(“elementId”));

Name: Locates elements using the name attribute value.

driver.findElement(By.name(“elementName”));

Class Name: Targets elements based on their CSS class name.

driver.findElement(By.className(“className”));

XPath: Provides a powerful way to navigate through the XML structure of a web page to find elements. XPath locators can traverse both the HTML and XML elements.

driver.findElement(By.xpath(“xpathExpression”));

CSS Selectors: CSS selectors identify elements by their CSS properties like ID, class, type, etc. They are powerful and efficient locators widely used in Selenium.

driver.findElement(By.cssSelector(“cssSelector”));

Link Text and Partial Link Text: These locate elements by the text displayed within anchor <a> tags.

driver.findElement(By.linkText(“linkText”));

driver.findElement(By.partialLinkText(“partialText”));

Deliver projects with confidence

  • Interacting with Web Elements: Perform actions like clicking buttons, entering text, selecting options from dropdowns (Static and Dynamic), etc., using WebDriver methods.
  • Waits and Synchronization: Implement waits to handle dynamic elements and synchronization issues using implicit, explicit, or fluent waits.

Implicit Waits: These waits set a default waiting time for the WebDriver to wait for an element before throwing a NoSuchElementException. Once set, this wait is applicable for the entire duration of the WebDriver object’s lifetime.

    Syntax:

        driver.manage().timeOut().implicitlyWait(Duration.ofSeconds(5));

Explicit Waits: These waits are applied to specific elements with specific conditions. You can instruct Selenium to wait until a certain condition is met before proceeding with the execution.

    Syntax:

         WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));

Some of the specific conditions for the explicit wait as follows:

  • alertIsPresent()
  • elementSelectionStateToBe()
  • elementToBeClickable()
  • elementToBeSelected()
  • frameToBeAvaliableAndSwitchToIt()
  • invisibilityOfTheElementLocated()
  • invisibilityOfElementWithText()
  • presenceOfAllElementsLocatedBy()
  • presenceOfElementLocated()
  • textToBePresentInElement()
  • textToBePresentInElementLocated()
  • textToBePresentInElementValue()
  • titleIs()
  • titleContains()
  • visibilityOf()
  • visibilityOfAllElements()
  • visibilityOfAllElementsLocatedBy()
  • visibilityOfElementLocated()

Fluent Waits: Fluent Wait in Selenium marks the maximum amount of time for Selenium WebDriver to wait for a certain condition (web element) becomes visible. It also defines how frequently WebDriver will check if the condition appears before throwing the “ElementNotVisibleException”.

     Syntax:

            Wait wait = new FluentWait(WebDriver reference)

            .withTimeout(timeout, SECONDS)

            .pollingEvery(timeout, SECONDS)

            .ignoring(Exception.class);

  • Handling Alerts, Frames, and Windows: Learn how to handle alerts, switch between frames, and manage multiple browser windows or tabs.

            Handling Alerts:

// Switching to an alert and accepting it

Alert alert = driver.switchTo().alert();

String alertMessage = alert.getText();

System.out.println(“Alert message: ” + alertMessage);

alert.accept();

Frames:

// Switching to a frame using index

driver.switchTo().frame(0);

// Switching back to default content

driver.switchTo().defaultContent();

// Switching to a frame using name or ID

driver.switchTo().frame(“frameName”);

// Identifying a frame using WebElement and switching to it

WebElement frameElement = driver.findElement(By.id(“frameId”));

driver.switchTo().frame(frameElement);

Supercharge your QA process

Picture of Indhu Priyanka K

Indhu Priyanka K

Meet Indhu Priyanka K, a seasoned manual tester whose passion for Quality Assurance (QA) has driven to explore the Automation testing. With a keen eye for detail and a commitment to enhancing efficiency and reducing manual effort in the testing process. Fueled by a curiosity to delve into testing tools and frameworks, Indhu Priyanka faced the initial challenges of progress into Selenium. Undeterred by the complexities. Recognizing the hurdles faced by newcomers in adopting Selenium, decided to share few insights by creating a comprehensive guide for Basic Selenium setup

All Posts

Deliver quality software with QA Touch

Questions? Explore our docs, videos, and more just one click away!

Real people with life changing results

Insights from QA Teams on QA Touch’s Impact

Frequently asked questions

Everything you need to know about the product and billing

Why QA Touch?

QA Touch is an AI-driven test management platform built by testers for testers. It simplifies collaboration between developers and QA engineers while helping to manage, track, and organize test cases efficiently. Streamline your testing processes, enhance QA visibility, and deliver high-quality software with ease.

QA Touch offers comprehensive features to manage the entire test management process. From easy migration with CSV files to audio-visual recording of issues and activity logs and a shareable dashboard for real-time reporting to stakeholders, we ensure the testing teams are always on top of things.

Our focus is on providing complete visibility and control over testing workflows and fostering collaboration between testers and other stakeholders (both internal and external). You can have a look at all the features here.

Once you sign up, it takes only 30 minutes to get your QA Touch account up and running. After registration, you will receive an account activation email with all the details. Log in with your account details and create your first test project on QA Touch—it’s that simple. You are now ready to start inviting your team and assigning them roles.

If you are finding it difficult to log in or facing any difficulty, feel free to reach our support team at info@qatouch.com

Why is QA Touch the best test management tool for me?

QA Touch is an AI-driven test management platform that simplifies collaboration between your developers and testers. Beyond creating, organizing, and executing test cases, QA Touch enables you to manage projects, track bugs, and monitor time—all in one platform.

With an intuitive UI and seamless two-way integrations, QA Touch adapts to your workflow, making test management, project oversight, and bug tracking smarter and more efficient.

With secure OKTA, Microsoft Azure SSO, and Google SSO enterprise features, you can stay connected in every app.

We have integrations with dozens of major apps like Slack, Jira, Monday.com, Cypress, and many more. Explore the whole list of integrations now supported here: Explore integrations

The test management tool is a modern software application that helps QA teams and developers manage their testing process efficiently. It provides a structured approach to creating, organizing, executing, and tracking tests to ensure software applications meet specified requirements and function properly before release.

Don’t just take our word for it.

QATouch is a leader in G2 market reports.