Selenium Cheatsheet

Screenshots

Use this Selenium reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Viewport Screenshot

save_screenshot() captures only the visible viewport — see below for true full-page capture.

# Save directly to a file
driver.save_screenshot("screenshot.png")

# Get PNG bytes in memory (no file written)
png_bytes = driver.get_screenshot_as_png()

# Get base64-encoded PNG string
b64_string = driver.get_screenshot_as_base64()

Element Screenshot

from selenium.webdriver.common.by import By

element = driver.find_element(By.ID, "chart-container")

# Save element screenshot to file
element.screenshot("chart.png")

# Get PNG bytes for the element
png_bytes = element.screenshot_as_png

# Get base64 string
b64_string = element.screenshot_as_base64

Working with PNG Bytes

import io
from PIL import Image

png_bytes = driver.get_screenshot_as_png()
img = Image.open(io.BytesIO(png_bytes))

print(img.size)       # (1920, 1080)
img.show()

# Crop a region
cropped = img.crop((100, 200, 500, 600))  # (left, top, right, bottom)
cropped.save("cropped.png")

# Convert to JPEG
img.convert("RGB").save("screenshot.jpg", quality=85)

Full-Page Screenshot

Selenium's standard save_screenshot does not capture below-the-fold content. Use one of these approaches:

Chrome DevTools Protocol (CDP) — Chrome/Edge only

# Requires Selenium 4 + a Chromium browser (execute_cdp_cmd)
result = driver.execute_cdp_cmd("Page.captureScreenshot", {
    "format": "png",
    "captureBeyondViewport": True,
    "clip": {
        "x": 0,
        "y": 0,
        "width":  driver.execute_script("return document.body.scrollWidth"),
        "height": driver.execute_script("return document.body.scrollHeight"),
        "scale": 1
    }
})

import base64
with open("full-page.png", "wb") as f:
    f.write(base64.b64decode(result["data"]))

Firefox Built-In Full-Page Capture

# Firefox driver has native full-page methods
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://example.com")

# Firefox-specific: get_full_page_screenshot_as_file / _as_png / _as_base64
driver.get_full_page_screenshot_as_file("full-page.png")
png = driver.get_full_page_screenshot_as_png()
b64 = driver.get_full_page_screenshot_as_base64()

Tall-Viewport Fallback (any browser, headless)

# Approximation: resize the window to the page height, then take a
# normal viewport screenshot. Works cross-browser in headless mode.
driver.get("https://example.com")
height = driver.execute_script("return document.body.scrollHeight")
driver.set_window_size(1440, height)
driver.save_screenshot("full-page.png")

Screenshot Utilities

Timestamp-Named Screenshot

from datetime import datetime

def take_screenshot(driver, prefix="screenshot"):
    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
    path = f"{prefix}_{ts}.png"
    driver.save_screenshot(path)
    return path

path = take_screenshot(driver, "login_page")
print(f"Saved to {path}")

Screenshot on Test Failure (pytest)

import pytest

@pytest.fixture
def driver():
    from selenium import webdriver
    d = webdriver.Chrome()
    yield d
    d.quit()

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.failed:
        driver = item.funcargs.get("driver")
        if driver:
            driver.save_screenshot(f"failure_{item.name}.png")

Screenshot Comparison (Pixel Diff)

from PIL import Image, ImageChops
import io

def screenshot_bytes(driver):
    return driver.get_screenshot_as_png()

def images_match(bytes1, bytes2, threshold=0):
    img1 = Image.open(io.BytesIO(bytes1))
    img2 = Image.open(io.BytesIO(bytes2))
    diff = ImageChops.difference(img1, img2)
    bbox = diff.getbbox()
    return bbox is None   # True if identical

baseline = screenshot_bytes(driver)
# ... interact with the page ...
current  = screenshot_bytes(driver)
assert images_match(baseline, current), "Visual regression detected"

Gotchas

driver.save_screenshot() only captures the current viewport, not below-the-fold content. Use CDP or Firefox's full-page method for the whole page.

Element screenshots respect the element's bounding box — if the element is partially off-screen or clipped, the screenshot reflects what the browser renders.

Headless screenshots may differ in size and font rendering compared to headed mode. Set an explicit --window-size when using --headless.

get_screenshot_as_png() returns raw bytes, not a file path. Pass it to io.BytesIO before opening with Pillow.