Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • DSA
  • Practice Problems
  • C
  • C++
  • Java
  • Python
  • JavaScript
  • Data Science
  • Machine Learning
  • Courses
  • Linux
  • DevOps
  • SQL
  • Web Development
  • System Design
  • Aptitude
  • GfG Premium
Open In App
Next Article:
Selenium Python Tutorial
Next article icon

Selenium with Java Tutorial

Last Updated : 29 Apr, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Deep dive into the powerful world of automated web testing and learn how to harness the capabilities of Selenium with Java, from setting up your environment to writing effective test scripts. Whether you're new to automated testing or looking to upscale your skills, this Selenium with Java tutorial will equip you with the knowledge to create robust and reliable tests for web applications.

Selenium is a widely used tool for testing web-based applications to see if they are doing as expected. It is a prominent preference amongst testers for cross-browser testing and is viewed as one of the most reliable systems for web application automation evaluation. Selenium is also platform-independent, so it can provide distributed testing using the Selenium Network.

Table of Content

  • How does Selenium Work?
  • Why Select Selenium with Java?
  • Steps to Configure Java Environment
  • Create a Selenium with Java Project in Eclipse
  • Steps for Writing Code

Its features, reach, and strong community assistance make it a powerful device for effective web application testing. The tutorial starts with basic concepts like setting up Selenium WebDriver and navigating web elements. It then moves into more advanced topics, such as handling dynamic elements, managing waits, automating form submissions, and using frameworks like TestNG for creating structured test scripts. This tutorial is ideal for beginners and advanced users who want to efficiently create test automation suites with real-world examples.

To get started, visit the full course here.

What is Selenium with Java

Selenium with Java refers to the combination of Selenium, a popular tool for automating web browsers, with the Java programming language. Selenium specifically, is used with Java to create automated tests for web applications. Java provides a robust and versatile environment for writing Selenium scripts, offering features such as object-oriented programming, extensive libraries, and platform independence. This combination enables developers and testers to automate interactions with web elements, simulate user actions, and verify expected behavior across different browsers and operating systems.

How Does Selenium Work?

Working for the Selenium WebDrive is explained below:

  1. User code: The user creates automation scripts. These scripts contain instructions and commands for interacting with web elements and web pages.
  2. Selenium Client Library: This library acts as a bridge between user code and WebDriver. It provides several APIs that allow user code to control web browsers and facilitate web interaction commands.
  3. WebDriver API: The WebDriver API defines custom instructions for internet interfaces. Various browser providers have applied their own WebDriver implementations, which can be well-matched with this API. It establishes a common language for browser automation.
  4. Browser-precise driving force: Each browser (e.g., Chrome, Firefox) has its personal WebDriver implementation (e.g., ChromeDriver, GeckoDriver). These drivers are liable for starting a specific browser and setting up a conversation channel with the WebDriver.
  5. Browser: The Webdriver sends commands to the browser to execute specific actions, like clicking elements or inputting text, which the browser then carries out accordingly.

Architecture of Selenium WebDriver

Why Select Selenium with Java?

Below we have mentioned the reasons to choose Selenium with Java for testing the application.

  1. Versatility: Java is one of the most typically used languages for web automation examining. It holds a massive matter of libraries and programs under Selenium WebDriver.
  2. Compatibility and Stability: Selenium has superior service Java making it a very compatible and robust integration.
  3. Ease of Learning and Use: Java is known for its readability and ease of learning, rendering it accessible for both amateurs and advanced coders.
  4. Large Community: Java has a large group of developers and inspectors using Selenium and Java which furnish valuable information, maintenance, CE, and solutions to common issues and struggles encountered by Selenium users.
Why Select Selenium with Java

Steps to Configure Java Environment

Step 1: Firstly, configure the Java Development Kit on your system. If not configured, then refer to the following installation steps here.

Step 2: Ensure that Java has been successfully installed on your system by running the command.

java -version

Step 3: Now, install an Integrated Development Environment (IDE) such as Eclipse, IntelliJ IDEA, or NetBeans. For this, we are using Eclipse so download it from here.

Step 4: Install the Selenium WebDriver library for Java. Download it from here. Extract the Zip File and complete the installation.

Step 5: We need web browsers such as Chrome, Firefox, Edge, or Safari. So, for this article demonstration, we will use the Chrome browser. A ChromeDriver executable file that matches your Chrome version. Download the latest release from here.

Step 6: Extract the zip file and copy the path where the chromedriver.exe file is, it is required in further steps. (e.g. - D:/chromedriver_win32/chromedriver.exe)
Extract Zip file

Create a Selenium with Java Project in Eclipse

Step 1: Launch Eclipse and select File -> New -> Java Project.

Create Java Project

Step 2: Enter a name for your project (e.g., SeleniumJavaTutorial) and click Finish.

Create Java Project

Step 3: Right-click on your project in Package Explorer and select Properties.

Select Properties

Step 4: Select Java Build Path from the left panel click on the libraries tab and then select Classpath. Click on Add External JARs and browse to the location where you downloaded the Selenium WebDriver library (e.g., selenium-java-4.1.0.zip).

Add External JARs

Step 5: Select all the JAR files inside the zip file and click Open and also all the files inside the lib folder. (D:\selenium-java-4.11.0, D:\selenium-java-4.11.0\lib).

Select JAR files

Step 6: Click Apply and Close to save the changes.

Save changes

Step 7: Create a new package under your project by right-clicking on the src folder and selecting New -> Package.

Create New Package

Step 8: Add the name of your package (e.g., WebDriver)

Add name of Package

Step 9: Create a new class under your package (e.g., WebDriver) by right-clicking on the package and selecting New -> Class, then Enter a name for your class and click Finish.

Create New Class

Step 10: After all the steps your file structure looks like this.

File Structure

Steps for Writing Code

Step 1: Import the required packages at the top of your class:

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

After importing if still getting errors in import just delete the module-info.java file.

Step 2: Create a main class inside the Web class.

public class Web {

public static void main(String[] args) {

}

}

Step 3: Set the system property for ChromeDriver (path to chromedriver executable). (e.g., D:/chromedriver_win32/chromedriver.exe)

System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");

Step 4: Create an instance of ChromeDriver.

WebDriver driver = new ChromeDriver();

Step 5: Navigate to the desired website.

driver.get("https://www.geeksforgeeks.org/");

Step 6: Get and print the page title.

String pageTitle = driver.getTitle();

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

Step 7: Wait for a few seconds.

try {

Thread.sleep(3000);

} catch (InterruptedException e) {

e.printStackTrace();

}

Step 8: Close the browser.

driver. Quit();

Below is the Java program to implement the above approach:

Java
package WebDriver;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Web {
    public static void main(String[] args) {
        // Set the system property for ChromeDriver (path to chromedriver executable)
        System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");

        // Create an instance of ChromeDriver (launch the Chrome browser)
        WebDriver driver = new ChromeDriver();

        try {
            // Navigate to the desired website (GeeksforGeeks in this example)
            driver.get("https://www.geeksforgeeks.org/");

            // Get and print the page title
            String pageTitle = driver.getTitle();
            System.out.println("Page Title: " + pageTitle);

            // Wait for a few seconds (for demonstration purposes only)
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // Close the browser
            driver.quit();
        }
    }
}

Output:
ggeks-selium

Conclusion

This Selenium with Java tutorial has shown you how to automate web testing using Selenium and Java. Through this tutorial you've learned everything from setting up your tools to writing effective test scripts. Now, you're ready to improve testing efficiency and ensure your web applications work smoothly.


Next Article
Selenium Python Tutorial

T

the_ravisingh
Improve
Article Tags :
  • Geeks Premier League
  • Software Testing
  • Selenium
  • selenium
  • Geeks Premier League 2023

Similar Reads

    Selenium Python Tutorial
    Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python , Java , C# , etc, we will be working with Python. Selenium Tutorial cover
    9 min read
    Junit Test with Selenium WebDriver
    Selenium is a browser automation tool that is used for testing purposes while Junit is a unit testing framework and by integrating them both we can write an automation test that will give the direct result of assertions. Junit is used with Java applications and Java also supports Selenium thus, we c
    8 min read
    Run Selenium Tests with Gauge
    Gauge is an open-source framework for test automation that is especially useful for Behavior Driven Development (BDD). It is characterized by its simplicity, scalability, and compatibility with other languages, such as Java, C#, and JavaScript. Gauge and Selenium work together to provide reliable, u
    5 min read
    How to Use AutoIT with Selenium Webdriver?
    Selenium WebDriver has revolutionized web automation, but it faces limitations when dealing with native Windows dialogs. This is where AutoIT comes to the rescue, bridging the gap between web and desktop automation. For testers and developers working on web applications, understanding how to integra
    8 min read
    How to Configure Selenium in Eclipse with Java
    Selenium is a suite of open-source tools and libraries used for automating web browsers. It enables users to write and execute scripts that interact with web elements, mimicking user actions such as clicking buttons, filling out forms, and navigating through web pages. Selenium supports multiple pro
    3 min read
    Selenium Tool Suite
    Selenium is a very well-known open-source software suite, mainly used for testing web browsers and web applications by automating some processes. It comes with a set of tools and libraries that allow developers or testers to automate some functions related to web browsers and web applications. Selen
    7 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences