Selenium Cheatsheet

Alerts and Cookies

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

JavaScript Alerts

Types of Alerts

Dialog Typealert()confirm()prompt()
Text visibleYesYesYes
Has OK buttonYesYesYes
Has Cancel buttonNoYesYes
Accepts inputNoNoYes

Switching to an Alert

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Wait for alert to appear
wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())

alert = driver.switch_to.alert

Alert Methods

MethodDescription
alert.textGet the alert message text
alert.accept()Click OK / Accept
alert.dismiss()Click Cancel / Dismiss
alert.send_keys(text)Type into a prompt() dialog
# Simple alert — just accept
alert = driver.switch_to.alert
print(alert.text)    # "Are you sure?"
alert.accept()

# Confirm dialog — accept or dismiss
alert.accept()    # click OK
alert.dismiss()   # click Cancel

# Prompt dialog — type a value then accept
alert.send_keys("my input text")
alert.accept()

Full Alert Pattern

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import UnexpectedAlertPresentException

driver.find_element(By.ID, "delete-btn").click()

try:
    WebDriverWait(driver, 5).until(EC.alert_is_present())
    alert = driver.switch_to.alert
    print(f"Alert says: {alert.text}")
    alert.accept()
except:
    print("No alert appeared")

Unexpected Alerts

from selenium.common.exceptions import UnexpectedAlertPresentException

try:
    driver.find_element(By.ID, "submit").click()
except UnexpectedAlertPresentException as e:
    print(f"Unexpected alert: {e.alert_text}")
    driver.switch_to.alert.accept()

Cookies

Reading Cookies

# All cookies for the current domain
cookies = driver.get_cookies()
print(cookies)
# [{"name": "session", "value": "abc123", "domain": "example.com", ...}, ...]

# Single cookie by name
cookie = driver.get_cookie("session_id")
print(cookie)     # dict or None
print(cookie["value"])

Adding and Modifying Cookies

# Must navigate to the domain first
driver.get("https://example.com")

# Basic add
driver.add_cookie({"name": "token", "value": "xyz789"})

# Full cookie dict
driver.add_cookie({
    "name":     "token",
    "value":    "xyz789",
    "domain":   "example.com",
    "path":     "/",
    "secure":   True,
    "httpOnly": False,
    "expiry":   1893456000,   # Unix timestamp
    "sameSite": "Strict"      # "Strict" | "Lax" | "None"
})

Deleting Cookies

driver.delete_cookie("session_id")     # delete by name
driver.delete_all_cookies()            # delete all cookies for current domain

Cookie Injection Pattern (bypass login)

# 1. Navigate to the target domain
driver.get("https://app.example.com")

# 2. Inject the session cookie
driver.add_cookie({
    "name":   "sessionid",
    "value":  "your-valid-session-token",
    "domain": "app.example.com",
    "path":   "/"
})

# 3. Refresh to apply the cookie
driver.refresh()

# 4. Confirm login worked
assert "Dashboard" in driver.title

Saving and Restoring Cookies (Cross-Session)

import json

# Save
cookies = driver.get_cookies()
with open("cookies.json", "w") as f:
    json.dump(cookies, f)

# Restore in a new session
driver.get("https://example.com")   # must be on the domain first
with open("cookies.json", "r") as f:
    cookies = json.load(f)

for cookie in cookies:
    # Some fields may cause errors; strip them if needed
    cookie.pop("expiry", None)
    driver.add_cookie(cookie)

driver.refresh()

Local Storage and Session Storage

# Local Storage
driver.execute_script("localStorage.setItem('key', 'value');")
val = driver.execute_script("return localStorage.getItem('key');")
driver.execute_script("localStorage.removeItem('key');")
driver.execute_script("localStorage.clear();")

# Session Storage
driver.execute_script("sessionStorage.setItem('key', 'value');")
val = driver.execute_script("return sessionStorage.getItem('key');")
driver.execute_script("sessionStorage.clear();")

# Get all keys
keys = driver.execute_script("return Object.keys(localStorage);")

Gotchas

You must be on the correct domain before adding cookies. add_cookie() silently ignores cookies for other domains without raising an error.

httpOnly cookies cannot be read or set via JavaScript (including localStorage workarounds). Selenium's add_cookie() is the only way to inject them.

alert.send_keys() followed by alert.dismiss() types into a prompt and then cancels — the typed value is not submitted.

UnexpectedAlertPresentException is raised by some drivers if an alert is open when you try to interact with the page. Always dismiss alerts before continuing.