WebDriver, locators, actions, waits, page factory, Grid, headless testing, and framework patterns.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.support.ui.*;
import java.time.Duration;
public class SeleniumSetup {
// ── Basic WebDriver Setup (Chrome) ──
public static WebDriver createDriver() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--window-size=1920,1080");
options.addArguments("--disable-gpu");
ChromeDriver driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
driver.manage().window().maximize();
return driver;
}
// ── Navigate & Basic Operations ──
public static void basicOperations(WebDriver driver) {
driver.get("https://example.com");
String title = driver.getTitle();
String currentUrl = driver.getCurrentUrl();
String pageSource = driver.getPageSource();
driver.navigate().to("https://example.com/page2");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();
// Window management
driver.manage().window().maximize();
driver.manage().window().fullscreen();
driver.manage().window().setSize(new Dimension(1920, 1080));
driver.manage().window().setPosition(new Point(0, 0));
// Cookies
driver.manage().addCookie(new Cookie("name", "value"));
Cookie cookie = driver.manage().getCookieNamed("name");
driver.manage().deleteCookieNamed("name");
driver.manage().deleteAllCookies();
}
}| Locator | Method | Example |
|---|---|---|
| ID | By.id() | By.id("username") |
| Name | By.name() | By.name("email") |
| Class Name | By.className() | By.className("btn-primary") |
| Tag Name | By.tagName() | By.tagName("button") |
| CSS Selector | By.cssSelector() | By.cssSelector("#login .btn") |
| XPath | By.xpath() | By.xpath("//input[@type="email"]") |
| Link Text | By.linkText() | By.linkText("Sign In") |
| Partial Link | By.partialLinkText() | By.partialLinkText("Sign") |
| Priority | Locator | Why |
|---|---|---|
| 1 (Best) | ID / Name | Unique, fast, stable |
| 2 | CSS Selector | Flexible, widely supported |
| 3 | XPath | Powerful but can be slow/fragile |
| 4 | Class / Tag | May match multiple elements |
| 5 (Worst) | Text-based | Breaks with i18n changes |
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.*;
import org.openqa.selenium.support.ui.*;
public class ActionsWaits {
// ── Element Interactions ──
public static void elementActions(WebDriver driver) {
WebElement input = driver.findElement(By.id("search"));
input.sendKeys("Selenium testing");
input.clear();
input.sendKeys(Keys.ENTER);
WebElement button = driver.findElement(By.cssSelector(".submit-btn"));
button.click();
// Select dropdown
Select dropdown = new Select(driver.findElement(By.id("country")));
dropdown.selectByVisibleText("United States");
dropdown.selectByValue("US");
dropdown.selectByIndex(0);
dropdown.deselectAll();
dropdown.getOptions();
dropdown.getFirstSelectedOption();
// Checkbox / Radio
WebElement checkbox = driver.findElement(By.id("agree"));
checkbox.click();
boolean isSelected = checkbox.isSelected();
boolean isDisplayed = checkbox.isDisplayed();
boolean isEnabled = checkbox.isEnabled();
}
// ── Advanced Actions ──
public static void advancedActions(WebDriver driver) {
Actions actions = new Actions(driver);
// Hover
WebElement menu = driver.findElement(By.id("nav-menu"));
actions.moveToElement(menu).perform();
// Drag and Drop
WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
actions.dragAndDrop(source, target).perform();
// Click and Hold
actions.clickAndHold(source).moveToElement(target).release().perform();
// Double click
actions.doubleClick(driver.findElement(By.id("item"))).perform();
// Right click
actions.contextClick(driver.findElement(By.id("item"))).perform();
// Keyboard shortcuts
actions.keyDown(Keys.CONTROL).sendKeys("a").sendKeys(Keys.DELETE)
.keyUp(Keys.CONTROL).perform();
}
// ── Explicit Waits ──
public static void explicitWaits(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for element visible
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("result"))
);
// Wait for element clickable
WebElement btn = wait.until(
ExpectedConditions.elementToBeClickable(By.cssSelector(".submit"))
);
// Custom condition
wait.until(d -> {
WebElement el = d.findElement(By.id("status"));
return el.getText().equals("Ready");
});
// Wait for alert
wait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();
}
// ── Frames & Windows ──
public static void framesWindows(WebDriver driver) {
// Switch to frame
driver.switchTo().frame("frameName");
driver.switchTo().frame(0); // by index
driver.switchTo().frame(driver.findElement(By.id("iframe")));
// Back to main content
driver.switchTo().defaultContent();
// Windows/Tabs
String mainWindow = driver.getWindowHandle();
driver.findElement(By.id("open-new")).click();
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(mainWindow)) {
driver.switchTo().window(handle);
driver.close();
}
}
driver.switchTo().window(mainWindow);
}
// ── JavaScript Execution ──
public static void jsExecution(WebDriver driver) {
JavascriptExecutor js = (JavascriptExecutor) driver;
// Scroll
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
// Click hidden element
js.executeScript("arguments[0].click();", driver.findElement(By.id("hidden-btn")));
// Get value
String value = (String) js.executeScript("return document.title");
// Highlight element
js.executeScript(
"arguments[0].style.border='3px solid red';",
driver.findElement(By.id("target"))
);
}
}// ── Page Object ──
public class LoginPage {
private WebDriver driver;
private WebDriverWait wait;
// Locators
private By emailInput = By.id("email");
private By passwordInput = By.id("password");
private By loginButton = By.cssSelector("button[type='submit']");
private By errorMessage = By.className("error-message");
private By forgotPassword = By.linkText("Forgot password?");
public LoginPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Verify we are on the right page
if (!driver.getCurrentUrl().contains("/login")) {
throw new IllegalStateException("Not on login page!");
}
}
public LoginPage enterEmail(String email) {
wait.until(ExpectedConditions.visibilityOfElementLocated(emailInput))
.sendKeys(email);
return this;
}
public LoginPage enterPassword(String password) {
wait.until(ExpectedConditions.visibilityOfElementLocated(passwordInput))
.sendKeys(password);
return this;
}
public DashboardPage clickLogin() {
wait.until(ExpectedConditions.elementToBeClickable(loginButton)).click();
return new DashboardPage(driver);
}
public DashboardPage loginAs(String email, String password) {
return enterEmail(email).enterPassword(password).clickLogin();
}
public String getErrorMessage() {
return wait.until(ExpectedConditions.visibilityOfElementLocated(errorMessage))
.getText();
}
public ForgotPasswordPage clickForgotPassword() {
driver.findElement(forgotPassword).click();
return new ForgotPasswordPage(driver);
}
}
// ── Test Using Page Object ──
public class LoginTest {
private WebDriver driver;
@Test
public void testSuccessfulLogin() {
LoginPage loginPage = new LoginPage(driver);
DashboardPage dashboard = loginPage.loginAs("user@example.com", "password123");
assertTrue(dashboard.isLoaded());
assertEquals("Welcome, User!", dashboard.getWelcomeMessage());
}
@Test
public void testInvalidLogin() {
LoginPage loginPage = new LoginPage(driver);
loginPage.loginAs("bad@example.com", "wrongpass");
assertEquals("Invalid email or password.", loginPage.getErrorMessage());
}
}| Benefit | Description |
|---|---|
| Reusability | Same page methods used across multiple tests |
| Maintainability | Change locator in one place |
| Readability | Tests read like user actions |
| Encapsulation | UI details hidden from tests |
| Separation | Business logic separate from page structure |
| Component | Purpose |
|---|---|
| Hub | Central point for test routing |
| Node | Machine executing the tests |
| Docker Selenium | Easiest local Grid setup |
| Cloud Grid | BrowserStack, SauceLabs, LambdaTest |
Implicit wait applies globally to all findElement calls. If the element is not found, it polls the DOM for the specified time before throwing NoSuchElementException. It only waits for element presence, not visibility or clickability.Explicit wait (WebDriverWait) waits for a specific condition on a specific element (visibility, clickability, text presence, etc.). It is more flexible, reliable, and faster. Always prefer explicit waits.
Selenium Grid distributes tests across multiple machines and browsers simultaneously. The Hub receives test requests and routes them to available Nodes. Use Grid when you need to run tests in parallel across different browsers (Chrome, Firefox, Safari), OS (Windows, macOS, Linux), or mobile platforms. This dramatically reduces test execution time. Modern setup uses Docker Selenium images for easy Grid deployment.