Locators, Waits & Interactions
Finding & Interacting with Elements
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement email = driver.findElement(By.id("email"));
email.sendKeys("user@example.com");
WebElement submit = driver.findElement(By.cssSelector("button[type=submit]"));
submit.click();
// findElements — returns an empty list if nothing matches, unlike findElement
List<WebElement> items = driver.findElements(By.className("list-item"));
// Selenium 4 relative locators — position relative to another element,
// useful when the target has no reliable ID/class of its own
WebElement emailLabel = driver.findElement(By.tagName("label"));
WebElement emailInput = driver.findElement(
RelativeLocator.with(By.tagName("input")).below(emailLabel));
driver.close(); // closes current window
driver.quit(); // closes ALL windows, ends the session — always call in teardownWaits — Explicit over Implicit
// Explicit wait — waits for a SPECIFIC condition, precise and preferred
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement result = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("result")));
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit"))).click();
// Implicit wait — a global timeout applied to EVERY findElement call
// driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
// Don't mix implicit + explicit — their polling can interact and produce
// a total wait time far longer than either configured value suggests.
// StaleElementReferenceException — the DOM node behind a cached reference
// was removed/re-rendered. Fix: re-locate the element right before use,
// don't cache it from much earlier in the test.
WebElement button = driver.findElement(By.id("toggle"));
button.click();
button = driver.findElement(By.id("toggle")); // re-fetch after the DOM changed
button.click();Actions, Alerts & Frames
// Actions class — complex interactions beyond a single click/sendKeys
new Actions(driver)
.moveToElement(menu)
.click(submenuItem)
.perform();
// Native dialogs — must switch context to interact
Alert alert = driver.switchTo().alert();
alert.accept(); // or .dismiss(), .getText(), .sendKeys("...")
// Iframes — same switchTo() mechanism
driver.switchTo().frame("payment-frame");
driver.findElement(By.id("card-number")).sendKeys("4242424242424242");
driver.switchTo().defaultContent(); // back to the main page
// Cookies — pre-seed an authenticated session, skip a repeated login flow
driver.manage().addCookie(new Cookie("session", token));Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free