Selenium with Java Tutorial
Selenium is a popular open-source tool used for automating web browsers. It supports multiple programming languages, including Java, Python, C#, etc. In this tutorial, we will cover how to use Selenium with Java for automating web applications.
1. Prerequisites
- Java Development Kit (JDK): Ensure you have JDK installed on your system. You can download it from Oracle’s official site.
- IDE (Integrated Development Environment): You can use IntelliJ IDEA, Eclipse, or any Java IDE.
- Selenium WebDriver: This is the core component used for automation. You’ll need to download it, or alternatively, add it as a Maven dependency.
- WebDriver (Browser Driver): For different browsers like Chrome, Firefox, etc., you need a browser-specific driver (e.g., ChromeDriver for Chrome).
2. Set up Selenium WebDriver with Java
Step 1: Install Java and Configure Your IDE
Ensure you have Java installed and your IDE is ready for development.
Step 2: Add Selenium Dependency (Maven)
If you’re using Maven, add the following dependency to your pom.xml
file:
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version> <!-- Use the latest version -->
</dependency>
</dependencies>
Step 3: Download WebDriver for your browser
- Chrome: Chrome Driver
- Firefox: Gecko Driver
Once downloaded, ensure the WebDriver is in your system PATH or provide its location explicitly in the code.
3. Write Your First Selenium Script
Here’s a simple example of a Selenium script in Java that opens a browser, navigates to a URL, and interacts with it:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumExample {
public static void main(String[] args) {
// Set the path to the WebDriver
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Initialize the WebDriver
WebDriver driver = new ChromeDriver();
// Open a website
driver.get("https://www.google.com");
// Print the title of the page
System.out.println("Page title: " + driver.getTitle());
// Close the browser
driver.quit();
}
}
Steps to Run:
- Download and configure the ChromeDriver executable.
- Set the system property for the WebDriver using
System.setProperty
. - Create an instance of
ChromeDriver
(or any other browser driver). - Use
driver.get("URL")
to navigate to a web page. - Use
driver.quit()
to close the browser once the test is complete.
4. Locating Elements
You can interact with web elements using different locating strategies:
- By ID:
driver.findElement(By.id("element_id")).click();
- By Name:
driver.findElement(By.name("element_name")).sendKeys("text");
- By XPath:
driver.findElement(By.xpath("//input[@name='username']")).sendKeys("testuser");
- By CSS Selector:
driver.findElement(By.cssSelector(".btn-primary")).click();
- By Link Text:
driver.findElement(By.linkText("Click Here")).click();
5. Waits in Selenium
Sometimes elements take time to load. To handle these situations, Selenium provides wait mechanisms.
- Implicit Wait: Set a default wait time for all elements.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
- Explicit Wait: Wait for a specific condition before proceeding.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("element_id")));
6. Handling Popups and Alerts
You can handle popups or JavaScript alerts using the Alert
interface.
// Accepting an alert
driver.switchTo().alert().accept();
// Dismissing an alert
driver.switchTo().alert().dismiss();
// Getting alert message
String alertMessage = driver.switchTo().alert().getText();
System.out.println(alertMessage);
// Sending keys to alert (for prompt alerts)
driver.switchTo().alert().sendKeys("text input");
7. Running Tests with TestNG
For better test management, you can use TestNG.
- Add the TestNG dependency to
pom.xml
:<dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.4.0</version> <!-- or latest version --> <scope>test</scope> </dependency>
- Create a simple TestNG test:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class GoogleTest { @Test public void testGoogleTitle() { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://www.google.com"); String title = driver.getTitle(); assert title.equals("Google"); driver.quit(); } }
- Run the tests with TestNG by right-clicking on the test class and selecting “Run as TestNG Test.”
8. Advanced Topics
- Handling Frames:
driver.switchTo().frame("frame_name_or_id"); driver.switchTo().defaultContent(); // Switch back to the main page
- Handling Multiple Windows:
String mainWindow = driver.getWindowHandle(); Set<String> allWindows = driver.getWindowHandles(); for (String windowHandle : allWindows) { driver.switchTo().window(windowHandle); } driver.switchTo().window(mainWindow); // Switch back to main window
- Taking Screenshots:
File screenshot =1;
Conclusion
This tutorial has provided a simple introduction to Selenium WebDriver with Java, including setup, interacting with web elements, waits, handling popups, and running tests using TestNG.
For more advanced usage, you can explore other Selenium features such as handling drop-downs, mouse movements, keyboard actions, and integrating Selenium with CI/CD tools.
- TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("screenshot.png" [↩]