Skip to content

Ferdinand Agyei-Yeboah

Working With Selenium In Java

March 25, 2023

Quickly showing how to get started with Selenium using Java and Maven. The setup step assumes Google Chrome is installed, but Selenium supports other major browsers as well (Firefox, Safari, etc…). The version of Chrome installed does not matter, the webdrivermanager dependency will pull the appropriate Selenium driver for your Chrome version.

Add Selenium Dependencies

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>4.0.0</version>
</dependency>

Setup Webdriver

WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
options.setHeadless(true); // true for no browser UI, false for live browser
WebDriver driver = new ChromeDriver(options);

Basic Usage

Navigate to Url

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

Finding elements

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
WebElement elementById = driver.findElement(By.id("elementId"));
WebElement elementByClass = driver.findElement(By.className("className"));
WebElement elementByName = driver.findElement(By.name("name"));
WebElement elementByXPath = driver.findElement(By.xpath("//xpath"));
WebElement elementByCssSelector = driver.findElement(By.cssSelector("cssSelector"));

Interacting with elements

element.sendKeys("text"); // Enter text into an input field
element.click(); // Click on an element
element.clear(); // Clear the text in an input field
element.getText(); // Get the text of an element
element.getAttribute("attributeName"); // Get the value of an attribute
element.isSelected(); // Check if a checkbox or radio button is selected
element.isEnabled(); // Check if an element is enabled

Executing JavaScript

import org.openqa.selenium.JavascriptExecutor;
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("JavaScript code");

Navigating between windows

String mainWindow = driver.getWindowHandle(); // Store the main window handle
Set<String> windows = driver.getWindowHandles();
for (String window : windows) {
if (!window.equals(mainWindow)) {
driver.switchTo().window(window);
break;
}
}
// Switch back to the main window
driver.switchTo().window(mainWindow);

Taking screenshots

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File("path/to/save/screenshot.png"));


Software Engineering Tutorials & Best Practices