Viden Corporation Viden Corporation | Selenium WebDriver Training Environment Training Only | 📞 (855) 843-3601 | ✉ info@videncorporation.com

🧪 Selenium Python Cheatsheet

All key WebDriver commands with examples tied to elements on SeleniumShop.

⚙️ Setup & Driver Init

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# Standard launch
driver = webdriver.Chrome()

# With options (headless)
opts = Options()
opts.add_argument("--headless")
opts.add_argument("--window-size=1920,1080")
driver = webdriver.Chrome(options=opts)

# Always clean up
driver.quit()

🔍 Locators

By.IDBy.CLASS_NAMEBy.NAMEBy.CSS_SELECTORBy.XPATH
from selenium.webdriver.common.by import By

# By ID — fastest and most reliable
driver.find_element(By.ID, "search-box")
driver.find_element(By.ID, "login-btn")
driver.find_element(By.ID, "product-p001")

# By Name attribute
driver.find_element(By.NAME, "username")
driver.find_element(By.NAME, "sort_by")

# By Class Name
driver.find_element(By.CLASS_NAME, "add-to-cart")
driver.find_elements(By.CLASS_NAME, "product-card") # returns list

# By CSS Selector
driver.find_element(By.CSS_SELECTOR, "#cart-count")
driver.find_element(By.CSS_SELECTOR, ".product-card:first-child .add-to-cart")
driver.find_element(By.CSS_SELECTOR, "[data-testid='search-input']")

# By XPath
driver.find_element(By.XPATH, "//button[@id='login-btn']")
driver.find_element(By.XPATH, "//h3[contains(text(),'Earbuds')]")
driver.find_element(By.XPATH, "//table[@id='cart-table']//tr[1]/td[1]")

# By Tag Name / Link Text
driver.find_elements(By.TAG_NAME, "button")
driver.find_element(By.LINK_TEXT, "View Cheatsheet")
driver.find_element(By.PARTIAL_LINK_TEXT, "Cheatsheet")

🖱️ Element Interactions

el = driver.find_element(By.ID, "search-box")

# Click & type
el.click()
el.send_keys("wireless earbuds")
el.clear()             # clear field

# Reading state
el.text                  # visible text
el.get_attribute("value") # input value
el.get_attribute("href")  # link href
el.get_attribute("data-testid")
el.is_displayed()        # visible?
el.is_enabled()          # enabled?
el.is_selected()         # checkbox/radio selected?
el.tag_name              # "button", "input" etc.
el.size                  # {'height': 36, 'width': 200}
el.location              # {'x': 100, 'y': 250}

📝 Forms — Dropdowns, Checkboxes, Radio

from selenium.webdriver.support.ui import Select

# ── Dropdown ──────────────────────────────
sel = Select(driver.find_element(By.ID, "sort-select"))
sel.select_by_visible_text("Price: Low to High")
sel.select_by_value("price_asc")
sel.select_by_index(2)
print(sel.first_selected_option.text)
all_opts = [o.text for o in sel.options]

# ── Checkbox ──────────────────────────────
cb = driver.find_element(By.ID, "brand-stylemax")
if not cb.is_selected():
    cb.click()          # check it

# ── Radio Button ──────────────────────────
driver.find_element(By.ID, "rating-4").click()

# ── Date input ────────────────────────────
driver.find_element(By.ID, "reg-dob").send_keys("1995-08-20")

# ── File upload ───────────────────────────
driver.find_element(By.ID, "file-input").send_keys("/abs/path/file.pdf")

⏳ Waits

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

wait = WebDriverWait(driver, 10)   # 10s timeout

# Element visible
el = wait.until(EC.visibility_of_element_located((By.ID, "ajax-result")))

# Element clickable
btn = wait.until(EC.element_to_be_clickable((By.ID, "timer-btn")))

# Text present in element
wait.until(EC.text_to_be_present_in_element(
    (By.ID, "progress-status"), "Complete"
))

# Element disappears
wait.until(EC.invisibility_of_element_located((By.ID, "ajax-loader")))

# Element present in DOM
wait.until(EC.presence_of_element_located((By.ID, "product-title-loaded")))

# Number of elements
wait.until(EC.number_of_windows_to_be(2))

# Implicit wait (global — use sparingly)
driver.implicitly_wait(5)

🔔 Alerts, Confirms & Prompts

# On index.html: click #alert-simple, #alert-confirm, #alert-prompt

# Accept alert
driver.find_element(By.ID, "alert-simple").click()
alert = driver.switch_to.alert
print(alert.text)      # read alert text
alert.accept()          # click OK

# Dismiss confirm
driver.find_element(By.ID, "alert-confirm").click()
driver.switch_to.alert.dismiss()  # click Cancel

# Send keys to prompt
driver.find_element(By.ID, "alert-prompt").click()
a = driver.switch_to.alert
a.send_keys("SELENIUM20")
a.accept()

🖼️ iframes & Windows

# ── iframes (index.html #promo-iframe) ────
driver.switch_to.frame("promo-iframe")  # by name/id
driver.find_element(By.ID, "iframe-email").send_keys("test@email.com")
driver.find_element(By.ID, "iframe-submit").click()
driver.switch_to.default_content()      # back to main

# By WebElement
frame_el = driver.find_element(By.ID, "promo-iframe")
driver.switch_to.frame(frame_el)

# ── New Windows/Tabs (dynamic.html) ───────
original = driver.current_window_handle
driver.find_element(By.ID, "open-new-tab").click()

# Wait for new window and switch
WebDriverWait(driver, 5).until(EC.number_of_windows_to_be(2))
new_win = [w for w in driver.window_handles if w != original][0]
driver.switch_to.window(new_win)
print(driver.title)

# Close tab and return
driver.close()
driver.switch_to.window(original)

🎮 ActionChains

from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

actions = ActionChains(driver)

# Hover (index.html #hover-btn → shows #tooltip)
el = driver.find_element(By.ID, "hover-btn")
actions.move_to_element(el).perform()

# Drag & drop (index.html)
src = driver.find_element(By.ID, "drag-source")
tgt = driver.find_element(By.ID, "drag-target")
actions.drag_and_drop(src, tgt).perform()

# Key combos
inp = driver.find_element(By.ID, "key-input")
inp.send_keys(Keys.CONTROL, 'a')  # select all
inp.send_keys(Keys.RETURN)       # Enter
inp.send_keys(Keys.TAB)           # Tab
inp.send_keys(Keys.ESCAPE)        # Escape

# Right-click
actions.context_click(el).perform()

# Double-click
actions.double_click(el).perform()

# Click and hold, then release
actions.click_and_hold(src).move_to_element(tgt).release().perform()

⚡ JavaScript Executor

# Scroll to element
el = driver.find_element(By.ID, "newsletter-section")
driver.execute_script("arguments[0].scrollIntoView();", el)

# Scroll to bottom of page
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

# Click via JS (useful for hidden/overlapped elements)
driver.execute_script("arguments[0].click();", el)

# Set input value via JS
driver.execute_script("arguments[0].value = 'selenium@test.com';", el)

# Read from page
title = driver.execute_script("return document.title;")
count = driver.execute_script("return document.querySelectorAll('.product-card').length;")

# Highlight element (debugging)
driver.execute_script(
    "arguments[0].style.border='3px solid red';", el
)

✅ Assertions (pytest)

# Text content
assert "SeleniumShop" in driver.title
assert driver.find_element(By.ID, "cart-count").text == "1"

# Visibility
assert driver.find_element(By.ID, "login-success").is_displayed()
assert not driver.find_element(By.ID, "login-error").is_displayed()

# URL check
assert "login" in driver.current_url

# Element count
cards = driver.find_elements(By.CLASS_NAME, "product-card")
assert len(cards) == 6

# Attribute
assert driver.find_element(By.ID, "timer-btn").get_attribute("disabled") is not None

# Input value
assert driver.find_element(By.ID, "username").get_attribute("value") == "student@test.com"

📸 Screenshots

# Full page screenshot
driver.save_screenshot("homepage.png")

# Element screenshot
el = driver.find_element(By.ID, "product-grid")
el.screenshot("product_grid.png")

# Get as bytes (for reporting)
png_bytes = driver.get_screenshot_as_png()
b64 = driver.get_screenshot_as_base64()