Selenium cheatsheet
A one-page reference for Selenium. For WebDriver architecture and interview Q&A, see the complete guide.
๐ Full guide: Selenium โLocator strategiesโ
driver.findElement(By.id("username"));
driver.findElement(By.cssSelector(".btn-primary"));
driver.findElement(By.xpath("//button[text()='Submit']"));
Prefer id/CSS over XPath โ faster, more resilient to markup changes.
Waits (avoid the classic flakiness bug)โ
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
Never mix Thread.sleep() with explicit waits โ and never set both an
implicit and explicit wait globally, they compound unpredictably.
Page Object Modelโ
public class LoginPage {
private WebDriver driver;
private By username = By.id("username");
public void login(String user, String pass) {
driver.findElement(username).sendKeys(user);
driver.findElement(By.id("submit")).click();
}
}
Frames, alerts, windowsโ
driver.switchTo().frame("payment-frame");
driver.switchTo().alert().accept();
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
Selenium Gridโ
docker run -d -p 4444:4444 selenium/hub
docker run -d --link hub selenium/node-chrome
new RemoteWebDriver(new URL("http://hub:4444"), capabilities);
Distributes tests across many browsers/machines in parallel.
Actions APIโ
Actions actions = new Actions(driver);
actions.dragAndDrop(source, target).perform();
actions.moveToElement(menu).click(subItem).perform();
Common flakiness pitfallsโ
- Hardcoded sleeps instead of explicit waits.
- Stale element references after a page re-render.
- Not isolating test data โ parallel tests colliding on shared state.
Framework & CI notesโ
- Pair with TestNG/JUnit for assertions and parallel execution.
- Run headless in CI (
--headless=newChrome flag) for speed. - Screenshot on failure โ the highest-leverage CI debugging aid.