ACCELQ Logo
    Generic selectors
    Exact matches only
    Search in title
    Search in content
    Post Type Selectors

The Ultimate Selenium Cheat Sheet for Test Automation Engineers (2026 Edition)

Selenium Sheet hero
Written by Chaithanya M N
Reviewed by Balbodh Jha
Published on

Selenium remains the backbone of web test automation. The Selenium cheat sheet provides what a test automation engineer needs, like core WebDriver commands, a full Selenium WebDriver cheat sheet reference, a dedicated Selenium with Java cheat sheet, a Python Selenium cheat sheet, and a deep-dive Selenium locators cheat sheet. All these on a single page so you never have to bounce between five different bookmarked tabs again.

Whether you need a quick answer mid-sprint or you’re building an automation framework from scratch, the blog is organized so you can jump straight to the section you need.

What’s New in 2026

Selenium is an open-source framework for automating browsers. It lets test automation engineers simulate real user behavior, clicking, typing, navigating, uploading files programmatically in Chrome, Firefox, Edge, and Safari, or whichever language their team standardizes on.

This cheat sheet consolidates 4 resources engineers usually search for individually:

  1. Selenium WebDriver cheat sheet is core, language-agnostic commands.
  2. Selenium with Java cheat sheet is Java-specific syntax and framework setup.
  3. Python Selenium cheat sheet is Python-specific syntax and framework setup.
  4. Selenium locators cheat sheet is a complete reference for each locator strategy.

What’s Shifted in Selenium 4

  • W3C WebDriver Protocol is now the standard protocol Selenium communicates over instead of the old JSON Wire Protocol. This means more consistent, spec-compliant behavior across browser vendors.
  • Selenium Manager ships with Selenium 4.6+, automatically downloads and manages the right browser driver binary for you. In most setups, you no longer need to manually download chromedriver or set executable_path.
  • Relative Locators were introduced to let you locate elements based on their visual place relative to another element, useful for dynamically generated markup.
  • Native DevTools Protocol (CDP) support for network interception, console log capture, and performance metrics without third-party tools.

Save this Selenium cheat sheet page you should need for scripting, whether you work in Java, Python, or both.

Setup and Installation

Java Setup

Task Command / Snippet
Add Selenium (Maven) <dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.x.x</version>
</dependency>
Add Selenium (Gradle) implementation ‘org.seleniumhq.selenium:selenium-java:4.x.x’
Import import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

Python Setup

Task Command / Snippet
Install Selenium pip install -U selenium
Import from selenium import webdriver;

from selenium.webdriver.common.by import By

WebDriver Initialization (Java vs. Python)

Browser Java Python
Chrome WebDriver driver = new ChromeDriver(); driver = webdriver.Chrome()
Firefox WebDriver driver = new FirefoxDriver(); driver = webdriver.Firefox()
Edge WebDriver driver = new EdgeDriver(); driver = webdriver.Edge()
Safari (Mac only) WebDriver driver = new SafariDriver(); driver = webdriver.Safari()

Note: With Selenium Manager, you do not need to manually save or configure browser driver binaries in either language.

Headless Mode

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
WebDriver driver = new ChromeDriver(options);
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)

Selenium Locators Cheat Sheet

Locators are how Selenium finds elements in the DOM. Opting for the right strategy is the biggest factor in whether your tests are fast and stable, or flaky and slow. This section is your standalone Selenium locators cheat sheet, covering all strategies in both Java and Python.

Basic Locator Strategies

Locator Java Python
By ID driver.findElement(By.id(“id_value”)) driver.find_element(By.ID, “id_value”)
By Name driver.findElement(By.name(“name_value”)) driver.find_element(By.NAME, “name_value”)
By Class Name driver.findElement(By.className(“class_value”)) driver.find_element(By.CLASS_NAME, “class_value”)
By Tag Name driver.findElement(By.tagName(“tag_value”)) driver.find_element(By.TAG_NAME, “tag_value”)
By Link Text driver.findElement(By.linkText(“Click Me”)) driver.find_element(By.LINK_TEXT, “Click Me”)
By Partial Link Text driver.findElement(By.partialLinkText(“Click”)) driver.find_element(By.PARTIAL_LINK_TEXT, “Click”)
By CSS Selector driver.findElement(By.cssSelector(“a.button”)) driver.find_element(By.CSS_SELECTOR, “a.button”)
By XPath driver.findElement(By.xpath(“//a[@id=’btn’]”)) driver.find_element(By.XPATH, “//a[@id=’btn’]”)

Deep Dive into CSS Selectors

CSS selectors are faster and readable than XPath for most use cases.

Pattern Example Matches
Class .btn-primary Elements with class btn-primary
ID #submit Element with id submit
Attribute input[type=’email’] Inputs with type=”email”
Descendant combinator div.card a Any <a> inside div.card
Direct child combinator ul > li <li> that is a direct child of <ul>
Pseudo-class li:nth-child(2) The second <li> in a list
Attribute contains [class*=’btn’] Any class attribute containing “btn”

Deep Dive into XPath

XPath is more powerful for traversing up the DOM tree or matching on text content, at some cost to speed and readability.

Pattern Example Matches
Absolute path /html/body/div/form Exact DOM path
Relative path //input[@id=’email’] Any input with id email, anywhere in the DOM
Text match //button[text()=’Submit’] Button with exact visible text “Submit”
Partial text match //div[contains(text(), ‘Welcome’)] Div containing partial text
Attribute contains //input[contains(@class, ‘form’)] Input with class attribute containing “form”
Parent navigation //span[@class=’error’]/parent::div Parent <div> of a span with class “error”
Sibling navigation //label[text()=’Email’]/following-sibling::input Input immediately after a matching label

Relative Locators

Introduced in Selenium 4, relative locators let you identify elements based on their visual place on the page relative to other elements, useful when IDs and classes are unreliable.

import static org.openqa.selenium.support.locators.RelativeLocator.with;
WebElement emailField = driver.findElement(By.id("email"));
WebElement passwordField = driver.findElement(with(By.tagName("input")).below(emailField));
from selenium.webdriver.support.relative_locator import locate_with
password_field = driver.find_element(
    locate_with(By.TAG_NAME, "input").below((By.ID, "email"))
)

Available relative methods: above(), below(), toLeftOf(), toRightOf(), near().

Locating Elements in Shadow DOM

Elements inside a Shadow DOM are isolated from the main document and can’t be located with standard locators alone.

WebElement shadowHost = driver.findElement(By.cssSelector("shadow-host-selector"));
SearchContext shadowRoot = shadowHost.getShadowRoot();
WebElement shadowElement = shadowRoot.findElement(By.cssSelector("element-inside-shadow-dom"));
shadow_host = driver.find_element(By.CSS_SELECTOR, "shadow-host-selector")
shadow_root = shadow_host.shadow_root
shadow_element = shadow_root.find_element(By.CSS_SELECTOR, "element-inside-shadow-dom")

CSS vs. XPath: Which to Use

Factor CSS Selectors XPath
Speed Faster Slower (more overhead)
Readability Generally cleaner Can get verbose
Traverse up the DOM (parent) Not supported Supported
Match by text content Not supported Supported
Browser support Native, universally fast Depends on browser’s XPath engine
Recommended default Yes, when possible Use when you need text-matching or parent traversal

Actions and Interactions

Core Interactions

Action Java Python
Click element.click(); element.click()
Type text element.sendKeys(“text”); element.send_keys(“text”)
Clear field element.clear(); element.clear()
Get text String t = element.getText(); t = element.text
Get attribute element.getAttribute(“class”); element.get_attribute(“class”)
Submit a form form.submit(); form.submit()

Actions Class (Mouse/Keyboard Events)

Actions actions = new Actions(driver);
actions.contextClick(element).perform();       // right-click
actions.doubleClick(element).perform();        // double-click
actions.dragAndDrop(source, target).perform(); // drag and drop
actions.moveToElement(element).perform();      // hover
from selenium.webdriver.common.action_chains import ActionChains

actions = ActionChains(driver)
actions.context_click(element).perform()        # right-click
actions.double_click(element).perform()         # double-click
actions.drag_and_drop(source, target).perform() # drag and drop
actions.move_to_element(element).perform()      # hover       
        

JavaScript Executor

Useful for scrolling, toggling disabled fields, or any native Selenium commands can’t reach.

((JavascriptExecutor) driver).executeScript("window.scrollBy(0, 1000)");
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
driver.execute_script("window.scrollBy(0, 1000)")
driver.execute_script("arguments[0].scrollIntoView(true);", element)  
        

Waits and Synchronization

Flaky tests are almost always a waits issue. Use explicit waits over implicit waits wherever possible.

Implicit Wait

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.implicitly_wait(10)

Explicit Wait

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")));
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.ID, "email")))
    

ExpectedConditions Quick Reference

Condition Use Case
visibilityOfElementLocated Element exists and is visible
elementToBeClickable Element is visible and enabled
presenceOfElementLocated Element exists in DOM (may not be visible)
invisibilityOfElementLocated Element is no longer visible (e.g., loading spinner)
textToBePresentInElement Wait until element contains specific text
alertIsPresent Wait for a JS alert/confirm dialog
numberOfWindowsToBe Wait for a particular number of open windows/tabs

Anti-Patterns to Avoid

  • Thread.sleep() / time.sleep() hardcoded delays may slow down suites and don’t guarantee reliability.
  • Mixing implicit and explicit waits in the same script can result unpredictable, and difficult to debug timeouts.
  • Setting excessively long implicit waits globally silently slows down each element lookup in your suite.
Action Java Python
Go to URL driver.get(“https://example.com”); driver.get(“https://example.com”)
Back driver.navigate().back(); driver.back()
Forward driver.navigate().forward(); driver.forward()
Refresh driver.navigate().refresh(); driver.refresh()
Close tab driver.close(); driver.close()
Quit session driver.quit(); driver.quit()

Frame Switching

Action Java Python
By index driver.switchTo().frame(0); driver.switch_to.frame(0)
By name/ID driver.switchTo().frame(“frameName”); driver.switch_to.frame(“frameName”)
By WebElement driver.switchTo().frame(frameElement); driver.switch_to.frame(frame_element)
Back to main content driver.switchTo().defaultContent(); driver.switch_to.default_content()
To parent frame — driver.switch_to.parent_frame()

Window/Tab Handling

String original = driver.getWindowHandle();
Set<String> allHandles = driver.getWindowHandles();

for (String handle : allHandles) {
    if (!handle.equals(original)) {
        driver.switchTo().window(handle);
        break;
    }
}
    original = driver.current_window_handle

for handle in driver.window_handles:
    if handle != original:
        driver.switch_to.window(handle)
        break
    

Alerts

Action Java Python
Switch to alert Alert alert = driver.switchTo().alert(); alert = driver.switch_to.alert
Accept alert.accept(); alert.accept()
Dismiss alert.dismiss(); alert.dismiss()
Get text alert.getText(); alert.text

Dropdowns (Select Class)

Select dropdown = new Select(driver.findElement(By.id("dropdown_id")));
dropdown.selectByVisibleText("Option Text");
dropdown.selectByIndex(2);
dropdown.selectByValue("option_value");
from selenium.webdriver.support.ui import Select
dropdown = Select(driver.find_element(By.ID, "dropdown_id"))
dropdown.select_by_visible_text("Option Text")
dropdown.select_by_index(2)
dropdown.select_by_value("option_value")
    

Files, Screenshots and Cookies

File Upload

WebElement uploadElement = driver.findElement(By.id("fileUpload"));
uploadElement.sendKeys("C:\\path\\to\\file.jpg");
file_input = driver.find_element(By.ID, "file_upload_id")
file_input.send_keys("/path/to/file.jpg")
    

Note: Selenium can automate file uploads via sendKeys. But native OS file download dialogs are outside the browser’s DOM and can’t be controlled directly handle downloads via browser-specific config rather than dialog automation.

Reading Test Data (Python)

# CSV
import csv

with open("data.csv", "r") as file:
    for row in csv.reader(file):
        print(row)

# Excel (pandas)
import pandas as pd

data = pd.read_excel("data.xlsx")
for index, row in data.iterrows():
    print(row)
    

Screenshots

Type Java Python
Full page ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); driver.save_screenshot(“page.png”)
Single element element.getScreenshotAs(OutputType.FILE); element.screenshot(“element.png”)

Cookies

Action Java Python
Add cookie driver.manage().addCookie(new Cookie(“key”, “value”)); driver.add_cookie({“name”: “key”, “value”: “value”})
Get all cookies driver.manage().getCookies(); driver.get_cookies()
Delete one driver.manage().deleteCookieNamed(“key”); driver.delete_cookie(“key”)
Delete all driver.manage().deleteAllCookies(); driver.delete_all_cookies()

Exceptions and Troubleshooting Reference

A quick-lookup table for the errors you’ll hit often in actual test suites.

Exception Common Cause Fix
NoSuchElementException Locator is wrong, outdated, or element hasn’t loaded yet Add an explicit wait for element presence; verify the locator in DevTools
StaleElementReferenceException The DOM changed after the element was located (e.g., page re-render) Re-locate the element before interacting with it
ElementClickInterceptedException Another element (overlay, modal, sticky header) is blocking the click Scroll element into view; wait for overlay to disappear; use JS click as fallback
ElementNotInteractableException Element exists in DOM but is hidden, disabled, or has zero size Wait for elementToBeClickable; check CSS visibility
TimeoutException Explicit wait condition never became true within the timeout Increase timeout cautiously; verify the condition/locator is actually correct
NoAlertPresentException Code tries to switch to an alert that isn’t open Wait for alertIsPresent before switching
InvalidSelectorException Malformed CSS or XPath syntax Validate the selector manually in browser DevTools console first
SessionNotCreatedException Browser/driver version mismatch Let Selenium Manager handle driver versions automatically; update Selenium

Testing Frameworks and Scaling

TestNG (Java) vs. Pytest (Python)

Task TestNG (Java) Pytest (Python)
Basic test @Test public void testLogin() { … } def test_login(): assert …
Run tests mvn test pytest test_file.py
Run by tag/marker @Test(groups = “smoke”) @pytest.mark.smoke
Run specific marker mvn test -Dgroups=smoke pytest -m smoke
Data-driven testing @DataProvider @pytest.mark.parametrize
Setup/Teardown @BeforeMethod / @AfterMethod Fixtures (@pytest.fixture)

Page Object Model (POM)

public class LoginPage {
    WebDriver driver;

    By username = By.id("username");
    By password = By.id("password");
    By loginBtn = By.id("login");

    public LoginPage(WebDriver driver) { this.driver = driver; }

    public void login(String user, String pass) {
        driver.findElement(username).sendKeys(user);
        driver.findElement(password).sendKeys(pass);
        driver.findElement(loginBtn).click();
    }
}
class LoginPage:
    def __init__(self, driver):
        self.driver = driver
        self.username = (By.ID, "username")
        self.password = (By.ID, "password")
        self.login_btn = (By.ID, "login")

    def login(self, user, password):
        self.driver.find_element(*self.username).send_keys(user)
        self.driver.find_element(*self.password).send_keys(password)
        self.driver.find_element(*self.login_btn).click()
    

Parallel Execution

<suite name="ParallelSuite" parallel="tests" thread-count="4">
  <test name="Test1"><classes><class name="LoginTest"/></classes></test>
  <test name="Test2"><classes><class name="CheckoutTest"/></classes></test>
</suite>
pip install pytest-xdist
pytest -n 4
    

Selenium Grid 4 (Docker)

docker run -d -p 4444:4444 --name selenium-hub selenium/hub:latest

docker run -d --link selenium-hub:hub selenium/node-chrome:latest

CI/CD Snippet (GitHub Actions)

name: Selenium Tests
on: [push]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - run: pip install -r requirements.txt
      - run: pytest --headless

Emerging Practices Worth Watching

  • Several commercial platforms now offer locator “healing” that automatically adapts when an element’s ID or class changes, reducing maintenance overhead on large suites. Evaluate before adopting into critical paths.
  • Pairing Selenium via the axe-selenium-java or axe-core-python bindings lets you run WCAG compliance checks as part of your existing test flow rather than as a separate audit.

Conclusion

Selenium continues to power the majority of web test automation frameworks in 2026. So, having quick access to the right syntax without going through docs or switching between five bookmarked tabs makes a difference in how fast you can write, debug, and scale tests. Whether you’re searching for a Selenium cheat sheet, a Selenium WebDriver cheat sheet, a Selenium with Java cheat sheet, a Python Selenium cheat sheet, or a Selenium locators cheat sheet, this page is built to cover all five in one go.

Keep this blog as a reference at your desk; download the condensed, printable one-page PDF version of this Selenium cheat sheet, covering each command, locator, and syntax table above in a compact, print-ready layout. No signup friction just click, save, and start automating. Download the Selenium Cheat Sheet PDF.

LinkedIn
Chaithanya M N
Chaithanya M N
Content Writer
A curious individual who is eager to learn and loves to share her knowledge using simple conversational writing skills. While her calling is technology and reading up on marketing updates, she also finds time to pursue her interests in philosophy, dance and music.

You Might Also Like:

Test Automation PitfallsBlogTest AutomationTest Automation Pitfalls and How Teams Fix Them?
19 February 2026

Test Automation Pitfalls and How Teams Fix Them?

Test automation pitfalls often stem from brittle scripts, maintenance, & poor ownership. Learn why automation fails and how teams can fix it.
Migration from Test project to ACCELQBlogTest AutomationMigration From TestProject to ACCELQ
3 January 2023

Migration From TestProject to ACCELQ

Looking for an alternative tool to migrate from TestProject? Then look no further than ACCELQ, for it's the ideal solution for TestProject users.
Locators in Test AutomationBlogTest AutomationLocators in Test Automation: A Deep Dive
10 October 2024

Locators in Test Automation: A Deep Dive

Boost your test automation skills with our locator guide. Learn identification methods, types, & tips for creating efficient test scripts.

Get started on your Codeless Test Automation journey

Talk to ACCELQ Team and see how you can get started.