
1. WebDriver Setup
// Setup ChromeDriver WebDriver driver = new ChromeDriver(); // Setup FirefoxDriver WebDriver driver = new FirefoxDriver(); // Setup for other browsers WebDriver driver = new EdgeDriver();
2. Browser Navigation
driver.get("https://example.com"); // Opens a webpage driver.navigate().to("https://example.com"); // Navigate to URL driver.navigate().back(); // Go back in browser history driver.navigate().forward(); // Go forward in browser history driver.navigate().refresh(); // Refresh the webpage
3. Basic Browser Operations
driver.manage().window().maximize(); // Maximize window driver.manage().window().minimize(); // Minimize window driver.manage().window().fullscreen(); // Fullscreen String title = driver.getTitle(); // Get page title String url = driver.getCurrentUrl(); // Get current URL String source = driver.getPageSource(); // Get page source driver.quit(); // Close browser and end session driver.close(); // Close current window
4. Element Locators
// By ID WebElement element = driver.findElement(By.id("elementID")); // By Name WebElement element = driver.findElement(By.name("elementName")); // By Class Name WebElement element = driver.findElement(By.className("className")); // By Tag Name WebElement element = driver.findElement(By.tagName("input")); // By Link Text WebElement element = driver.findElement(By.linkText("Click Here")); // By Partial Link Text WebElement element = driver.findElement(By.partialLinkText("Click")); // By CSS Selector WebElement element = driver.findElement(By.cssSelector("input#elementID")); // By XPath WebElement element = driver.findElement(By.xpath("//input[@id='elementID']"));
5. Working with Web Elements
// Send text to an input field element.sendKeys("test data"); // Click on an element (button, link, etc.) element.click(); // Clear an input field element.clear(); // Get text from an element String text = element.getText(); // Get attribute value of an element String attribute = element.getAttribute("type"); // Check if element is displayed boolean isDisplayed = element.isDisplayed(); // Check if element is enabled boolean isEnabled = element.isEnabled(); // Check if element is selected (checkbox, radio button) boolean isSelected = element.isSelected();
6. Handling Dropdowns
// Locate the dropdown element WebElement dropdown = driver.findElement(By.id("dropdownID")); Select select = new Select(dropdown); // Select by visible text select.selectByVisibleText("Option 1"); // Select by value select.selectByValue("optionValue"); // Select by index select.selectByIndex(1); // Get selected option WebElement selectedOption = select.getFirstSelectedOption(); String selectedText = selectedOption.getText();
7. Handling Alerts
// Switch to alert Alert alert = driver.switchTo().alert(); // Accept alert (OK button) alert.accept(); // Dismiss alert (Cancel button) alert.dismiss(); // Get alert text String alertText = alert.getText(); // Send text to an alert (only for prompts) alert.sendKeys("text to send");
8. Handling Frames & iFrames
// Switch to frame by index driver.switchTo().frame(0); // Switch to frame by name or ID driver.switchTo().frame("frameName"); // Switch to frame using WebElement WebElement frameElement = driver.findElement(By.xpath("//iframe")); driver.switchTo().frame(frameElement); // Switch back to main content driver.switchTo().defaultContent();
9. Handling Multiple Windows
// Get current window handle String mainWindow = driver.getWindowHandle(); // Switch to another window for (String handle : driver.getWindowHandles()) { driver.switchTo().window(handle); } // Close the newly opened window and switch back to the main window driver.close(); driver.switchTo().window(mainWindow);
10. Handling Cookies
// Get all cookies Set<Cookie> cookies = driver.manage().getCookies(); // Add a cookie Cookie cookie = new Cookie("key", "value"); driver.manage().addCookie(cookie); // Delete a specific cookie driver.manage().deleteCookieNamed("cookieName"); // Delete all cookies driver.manage().deleteAllCookies();
11. Waits in Selenium
Implicit Wait:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Explicit Wait:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementID")));
Fluent Wait:
Wait<WebDriver> fluentWait = new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(30)) .pollingEvery(Duration.ofSeconds(5)) .ignoring(NoSuchElementException.class); WebElement element = fluentWait.until(driver -> driver.findElement(By.id("elementID")));
12. Mouse and Keyboard Actions
Actions Class:
Actions actions = new Actions(driver); // Hover over an element actions.moveToElement(element).perform(); // Double-click on an element actions.doubleClick(element).perform(); // Right-click (context click) on an element actions.contextClick(element).perform(); // Drag and drop actions.dragAndDrop(sourceElement, targetElement).perform(); // Click and hold, then release actions.clickAndHold(element).release().perform();
13. Taking Screenshots
// Take screenshot of the entire page File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("path/to/screenshot.png")); // Take screenshot of a specific element File screenshot = element.getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("path/to/element_screenshot.png"));
14. Running JavaScript in Selenium
JavascriptExecutor js = (JavascriptExecutor) driver; // Scroll down js.executeScript("window.scrollBy(0,500)"); // Click an element js.executeScript("arguments[0].click();", element); // Get page title via JavaScript String title = js.executeScript("return document.title;").toString();
15. Handling JavaScript Popups
// Example of clicking "OK" on a JS popup driver.switchTo().alert().accept();
javaCopy code
16. Headless Browser Execution
// For Chrome ChromeOptions options = new ChromeOptions(); options.addArguments("--headless"); WebDriver driver = new ChromeDriver(options); // For Firefox FirefoxOptions options = new FirefoxOptions(); options.addArguments("--headless"); WebDriver driver = new FirefoxDriver(options);
17. Assertions
Using TestNG:
Assert.assertEquals(actual, expected); // Validate equality Assert.assertTrue(condition); // Validate a condition Assert.assertFalse(condition); // Validate the condition is false Assert.assertNotNull(object); // Validate object is not null
18. Managing Timeouts
// Page load timeout driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS); // Script timeout driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
19. Handling File Uploads
// Use sendKeys to directly interact with the input element for file uploads driver.findElement(By.id("uploadElement")).sendKeys("path/to/file.png");
20. Common Exceptions
- NoSuchElementException: Element is not found.
- ElementNotVisibleException: Element is present but not visible.
- TimeoutException: Timeout has occurred before operation completes.
- StaleElementReferenceException: Element is no longer attached to the DOM.
This cheatsheet covers a wide range of Selenium WebDriver functionality and is up-to-date with the latest features for 2024. It’s designed to help testers automate browser testing efficiently.
Subscribe to QABash Weekly 💥
Dominate – Stay Ahead of 99% Testers!