Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 35 ยท Practice and Review

Selenium Cheat Sheet

A one-page Selenium cheat sheet with Python and Java side by side: locators, element actions, waits, switching, exceptions, browser options and Grid.

This page is a quick reference, not a lesson. It lines up the everyday Selenium WebDriver calls in Python and Java so you can look something up in seconds. Each section links back to the lesson that explains the idea.

Selenium needs a browser and driver, so every command below is read-only. The two stand-ins at the end are small JavaScript tools that run here: a searchable copy of part of this sheet and a locator translator. Method names follow Selenium 4. Check the documentation of your installed version when something does not behave as listed.

One page, seven shelves

Start Driver, navigation, quit.
Find Eight locator strategies.
Act Click, type, select, drag.
Wait Conditions, not sleep.

Follow the order of a test, from start to teardown.

1 / 2

Starting and navigating

Task Python Java
Start Chrome driver = webdriver.Chrome() WebDriver driver = new ChromeDriver();
Open a URL driver.get(url) driver.get(url);
Back / forward / refresh driver.back(), driver.forward(), driver.refresh() driver.navigate().back(), .forward(), .refresh()
Title driver.title driver.getTitle()
Current URL driver.current_url driver.getCurrentUrl()
Page HTML driver.page_source driver.getPageSource()
Close tab / end session driver.close() / driver.quit() driver.close(); / driver.quit();
Window size driver.set_window_size(1280, 900) driver.manage().window().setSize(new Dimension(1280, 900));
Maximize driver.maximize_window() driver.manage().window().maximize();

Always end with quit(), in a finally block or a fixture teardown. See Setup and Your First Script.

Locators

Strategy Python Java CSS equivalent
ID By.ID, "x" By.id("x") #x
Name By.NAME, "x" By.name("x") [name="x"]
Class By.CLASS_NAME, "x" By.className("x") .x (one class only)
Tag By.TAG_NAME, "h1" By.tagName("h1") h1
Link text By.LINK_TEXT, "Sign in" By.linkText("Sign in") none
Partial link text By.PARTIAL_LINK_TEXT, "Sign" By.partialLinkText("Sign") none
CSS selector By.CSS_SELECTOR, "form input" By.cssSelector("form input") itself
XPath By.XPATH, "//a[text()='Help']" By.xpath("//a[text()='Help']") none
Task Python Java
First match (raises if none) driver.find_element(By.ID, "x") driver.findElement(By.id("x"))
All matches (empty list if none) driver.find_elements(By.CSS_SELECTOR, "li") driver.findElements(By.cssSelector("li"))
Search inside an element row.find_elements(By.TAG_NAME, "td") row.findElements(By.tagName("td"))
Relative locator locate_with(By.TAG_NAME, "input").below({By.ID: "email"}) RelativeLocator.with(By.tagName("input")).below(By.id("email"))

The Python relative locator needs from selenium.webdriver.support.relative_locator import locate_with. Rank locators by stability: test id, plain id, name, short CSS, then XPath. See Locators, CSS Selector Locators, XPath Locators and Choosing Stable Locators.

Handy CSS patterns: [data-testid="save"], a[href^="/docs"] (starts with), a[href$=".pdf"] (ends with), li:nth-child(2), form > input (direct child). Handy XPath patterns: //button[normalize-space()='Save'], //input[contains(@class,'wide')], //td[text()='Ana']/following-sibling::td[1], //label[@for='email']/.. (parent).

Interacting with elements

Task Python Java
Click el.click() el.click();
Type el.send_keys("text") el.sendKeys("text");
Clear el.clear() el.clear();
Press a key el.send_keys(Keys.ENTER) el.sendKeys(Keys.ENTER);
Visible text el.text el.getText()
Attribute or property el.get_attribute("href") el.getAttribute("href")
Raw property el.get_property("value") el.getDomProperty("value")
Computed CSS el.value_of_css_property("color") el.getCssValue("color")
State el.is_displayed(), is_enabled(), is_selected() el.isDisplayed(), isEnabled(), isSelected()
Upload a file file_input.send_keys("/abs/path/a.png") fileInput.sendKeys("/abs/path/a.png");
Select by text Select(el).select_by_visible_text("Red") new Select(el).selectByVisibleText("Red");
Select by value / index select_by_value("r"), select_by_index(0) selectByValue("r"), selectByIndex(0)
Hover ActionChains(driver).move_to_element(el).perform() new Actions(driver).moveToElement(el).perform();
Double / right click .double_click(el), .context_click(el) .doubleClick(el), .contextClick(el)
Drag and drop .drag_and_drop(src, dst).perform() .dragAndDrop(src, dst).perform();
Key chord .key_down(Keys.CONTROL).send_keys("a").key_up(Keys.CONTROL).perform() .keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
Scroll to element ActionChains(driver).scroll_to_element(el).perform() new Actions(driver).scrollToElement(el).perform();
Run JavaScript driver.execute_script("return document.title") ((JavascriptExecutor) driver).executeScript("return document.title");

Python imports: from selenium.webdriver.common.keys import Keys, from selenium.webdriver.common.action_chains import ActionChains, from selenium.webdriver.support.ui import Select. See Clicking and Typing, Forms, Checkboxes and Dropdowns and the Actions API.

Waiting

Task Python Java
Implicit wait (keep at 0) driver.implicitly_wait(0) driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(0));
Explicit wait WebDriverWait(driver, 10).until(EC.visibility_of_element_located(loc)) new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(loc));
Fluent wait WebDriverWait(driver, 10, poll_frequency=0.5, ignored_exceptions=[NoSuchElementException]) new FluentWait<>(driver).withTimeout(Duration.ofSeconds(10)).pollingEvery(Duration.ofMillis(500)).ignoring(NoSuchElementException.class)
Condition Python (EC.) Java (ExpectedConditions.)
In the DOM presence_of_element_located(loc) presenceOfElementLocated(loc)
Visible visibility_of_element_located(loc) visibilityOfElementLocated(loc)
Clickable element_to_be_clickable(loc) elementToBeClickable(loc)
Gone / stale staleness_of(el), invisibility_of_element_located(loc) stalenessOf(el), invisibilityOfElementLocated(loc)
Text present text_to_be_present_in_element(loc, "Done") textToBePresentInElement(el, "Done")
URL / title url_contains("/home"), title_is("Home") urlContains("/home"), titleIs("Home")
Alert alert_is_present() alertIsPresent()
Frame frame_to_be_available_and_switch_to_it(loc) frameToBeAvailableAndSwitchToIt(loc)
Windows number_of_windows_to_be(2) numberOfWindowsToBe(2)

Python imports: from selenium.webdriver.support.ui import WebDriverWait and from selenium.webdriver.support import expected_conditions as EC. Never mix implicit and explicit waits, and never use sleep() as a synchronisation tool. See Why Tests Need Waits and Implicit, Explicit and Fluent Waits.

Alerts, frames, windows and cookies

Task Python Java
Accept / dismiss alert driver.switch_to.alert.accept() / .dismiss() driver.switchTo().alert().accept(); / .dismiss()
Alert text / type alert.text, alert.send_keys("x") alert.getText(), alert.sendKeys("x")
Enter a frame driver.switch_to.frame("name-or-id-or-element") driver.switchTo().frame("name-or-id-or-element");
Leave frames driver.switch_to.default_content() driver.switchTo().defaultContent();
One frame up driver.switch_to.parent_frame() driver.switchTo().parentFrame();
All windows driver.window_handles driver.getWindowHandles()
Current window driver.current_window_handle driver.getWindowHandle()
Switch window driver.switch_to.window(handle) driver.switchTo().window(handle);
Open new tab driver.switch_to.new_window("tab") driver.switchTo().newWindow(WindowType.TAB);
Add / read cookies driver.add_cookie({"name": "n", "value": "v"}), driver.get_cookies() driver.manage().addCookie(new Cookie("n", "v"));, getCookies()
Delete cookies driver.delete_all_cookies() driver.manage().deleteAllCookies();
Screenshot (page) driver.save_screenshot("a.png") ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE)
Screenshot (element) el.screenshot("e.png") el.getScreenshotAs(OutputType.FILE)

Selenium never switches to a new tab or frame for you, and you must switch back afterwards. See Alerts, Frames and Windows and File Uploads, Downloads and Screenshots.

Exceptions

Exception Usual meaning First thing to try
NoSuchElementException Locator matched nothing (yet) Check the locator in DevTools; wait for presence
StaleElementReferenceException Element was replaced after you found it Find it again after the change
ElementClickInterceptedException Something covers the target Wait for the overlay to go; scroll into view
ElementNotInteractableException Hidden, disabled or off-screen Wait for visible and enabled
TimeoutException An explicit wait ran out Review the condition, not just the time
NoSuchFrameException / NoSuchWindowException / NoAlertPresentException You switched to something not there Wait with the matching condition first
InvalidSelectorException Malformed CSS or XPath Test the selector in the DevTools console
SessionNotCreatedException Browser/driver mismatch or bad options Update; check capabilities
WebDriverException Generic driver or browser failure Read the message; check the driver log

Options, remote and Grid

Task Python Java
Chrome options options = webdriver.ChromeOptions() ChromeOptions options = new ChromeOptions();
Headless options.add_argument("--headless=new") options.addArguments("--headless=new");
Start with options webdriver.Chrome(options=options) new ChromeDriver(options)
Page load strategy options.page_load_strategy = "eager" options.setPageLoadStrategy(PageLoadStrategy.EAGER);
Browser preferences options.add_experimental_option("prefs", {...}) options.setExperimentalOption("prefs", Map.of(...));
Firefox / Edge webdriver.FirefoxOptions(), webdriver.EdgeOptions() new FirefoxOptions(), new EdgeOptions()
Remote (Grid) webdriver.Remote(command_executor="http://localhost:4444", options=options) new RemoteWebDriver(new URL("http://localhost:4444"), options)

Selenium Manager finds a matching driver automatically in current versions, so you rarely set driver paths. See Headless Mode and Browser Options and Selenium Grid.

Test skeletons

Python
import pytest
from selenium import webdriver

@pytest.fixture
def driver():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_title(driver):
    driver.get("https://example.test")
    assert "Example" in driver.title
Java
class TitleTest {
    WebDriver driver;

    @BeforeEach void setUp() { driver = new ChromeDriver(); }
    @AfterEach  void tearDown() { driver.quit(); }

    @Test void titleContainsExample() {
        driver.get("https://example.test");
        assertTrue(driver.getTitle().contains("Example"));
    }
}

See Selenium with pytest and Selenium with JUnit and TestNG.

Try the stand-ins

The first stand-in is a searchable copy of a few rows of this sheet. It shows how a cheat sheet can be treated as data: type some words and every row whose task contains all of them is listed.

JS Stand-in: search the cheat sheet

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in turns a locator strategy and value into the Python call, the Java call and, when one exists, the CSS equivalent. Strategies such as link text and XPath have no CSS form, and the tool says so.

JS Stand-in: locator translator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does find_elements return when nothing matches?

    Only find_element raises. find_elements returns an empty list.
  2. 2. Which call ends the whole browser session and stops the driver?

    close() only closes the current window. quit() ends the session.
  3. 3. Which locator strategy has no CSS selector equivalent?

    CSS selectors cannot match on the text of a link. Use link text or XPath for that.
  4. 4. After switching into an iframe, how do you return to the main page?

    default_content() (Java: defaultContent()) switches back to the top-level document.

Summary

  • Start a driver, navigate, and always end with quit().
  • Prefer test ids, ids and short CSS; use XPath for text and parent traversal.
  • find_element raises when nothing matches; find_elements returns an empty list.
  • Use explicit waits with conditions; keep the implicit wait at zero; never rely on sleep().
  • Switch deliberately to alerts, frames and windows, and switch back afterwards.
  • Learn the common exceptions: each one suggests a different fix.

You have reached the end of the Selenium course. Revisit the weak spots with Practice Exercises with Solutions, or start again from What Is Selenium?.