Setting Up Selenium WebDriver in Java: A Step-by-Step Guide
Here’s a step-by-step guide to setting up Selenium WebDriver with Java, including all the essentials to get you from zero to browser automation:
π§° Prerequisites
Before diving in, make sure you have:
Java JDK installed (JDK 8 or higher)
An IDE (like IntelliJ IDEA or Eclipse)
Maven or Gradle (recommended for dependency management)
A web browser (Chrome or Firefox)
π§ Step 1: Install Java & Set Environment Variables
Download JDK: https://www.oracle.com/java/technologies/javase-downloads.html
Set JAVA_HOME:
Windows: Add a system environment variable JAVA_HOME pointing to your JDK path.
Add %JAVA_HOME%\bin to the Path variable.
Verify with:
bash
Copy
Edit
java -version
javac -version
π‘ Step 2: Set Up Your Java Project
Option 1: Using Maven (Recommended)
Create a Maven project in your IDE.
Add Selenium dependency to your pom.xml:
xml
Copy
Edit
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.18.0</version> <!-- Check for latest version -->
</dependency>
</dependencies>
Option 2: Using Gradle
Add this to your build.gradle:
groovy
Copy
Edit
dependencies {
testImplementation 'org.seleniumhq.selenium:selenium-java:4.18.0'
}
π Step 3: Download the WebDriver Executable
Depending on the browser you want to automate:
ChromeDriver: https://sites.google.com/chromium.org/driver/
GeckoDriver (Firefox): https://github.com/mozilla/geckodriver/releases
Place the driver .exe somewhere on your system and add the path to your system PATH variable, or specify it in code.
π Step 4: Write Your First Selenium Script
Java Example:
java
Copy
Edit
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) {
// Optional: Set path if not in system PATH
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
✅ Step 5: Run the Code
Compile and run the class from your IDE or terminal.
You should see a browser open and navigate to Google, then print the page title.
π Bonus Tips:
Use WebDriverManager to manage drivers automatically:
xml
Copy
Edit
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.7.0</version>
</dependency>
java
Copy
Edit
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
Keep browser and driver versions in sync to avoid compatibility issues.
Want to add test frameworks like JUnit or TestNG? Or integrate with page object models? Let me know and I’ll guide you through those too!
Learn Selenium JAVA Course
Read More
Setting Up Selenium WebDriver in Java: A Step-by-Step Guide
From where I can get Selenium Java training in New York?
Visit Our IHUB Talent Training in Hyderabad
Comments
Post a Comment