This comprehensive Selenium+Python cheat sheet is designed to assist both beginners and experienced developers. It simplifies working with Selenium WebDriver, offering practical and concise solutions for key topics like setup, browser automation, and advanced commands.
Whether your goal is to automate browser tasks or scale tests across diverse environments, this guide delivers ready-to-use Python code snippets and actionable insights to streamline your test automation workflows efficiently.
| Key Takeaways: |
- Always prefer explicit waits (WebDriverWait) over implicit waits or time.sleep().
- Use modern locators via the By class because old methods are deprecated.
- File handling in Selenium means triggering downloads/uploads and validating them via Python.
- Avoid mixing languages.
- Follow best practices like headless execution and clean test structure such as `pytest` and POM.
|
Read our Selenium with Java Cheat Sheet: Selenium with Java Cheat Sheet.
Selenium Cheat Sheet with Python
Setup
| Task |
Command |
| Install Selenium |
pip install -U selenium |
| Setup and Import |
from selenium import webdriverfrom selenium.webdriver.common.by import By
from selenium.webdriver.common.by import By
|
WebDriver Setup
| Browser |
Command |
| Chrome |
driver = webdriver.Chrome() |
| Firefox |
driver = webdriver.Firefox() |
| Microsoft Edge |
driver = webdriver.Edge() |
| Safari (Only Mac) |
driver = webdriver.Safari() |
Note: With Selenium Manager, modern Selenium versions automatically handle browser driver setup. Driver installation and configuration are typically no longer required.
PyTest
| Task |
Example |
| Install Pytest |
pip install pytest |
| Basic Test |
import pytest
def test_example():
assert 1 + 1 == 2
|
| Run Tests |
pytest test_file.py |
| Run Specific Test |
pytest -k “test_name” |
| Run Tests in a Directory |
pytest tests/ |
| Markers |
@pytest.mark.smoke
def test_smoke_case():
assert True
|
| Run Specific Marker |
pytest -m smoke |
Unittest
| Task |
Example |
| Import Unittest |
import unittest |
| Create a Test Case |
class TestExample(unittest.TestCase):
def test_addition(self):
self.assertEqual(1 + 1, 2)
|
| Run Tests |
python -m unittest test_file.py |
| Setup and Teardown |
class TestExample(unittest.TestCase):
def setUp(self):
# Setup code
pass
def tearDown(self):
# Teardown code
pass
|
| Run All Tests in a Directory |
python -m unittest discover tests/ |
| Assert Methods |
assertEqual(a, b)
assertNotEqual(a, b)
assertTrue(x)
assertFalse(x)
assertIs(a, b)
assertIsNot(a, b)
|
Locators
| Locator |
Example |
| By ID |
driver.find_element(By.ID, “id_value”) |
| By Name |
driver.find_element(By.NAME, “name_value”) |
| By Class Name |
driver.find_element(By.CLASS_NAME, “class_value”) |
| By Tag Name |
driver.find_element(By.TAG_NAME, “tag_value”) |
| By Link Text |
driver.find_element(By.LINK_TEXT, “link_text_value”) |
| By Partial Link Text |
driver.find_element(By.PARTIAL_LINK_TEXT, “partial_link”) |
| By CSS Selector |
driver.find_element(By.CSS_SELECTOR, “css_selector”) |
| By XPath |
driver.find_element(By.XPATH, “xpath_value”) |
| Relative Locators |
from selenium.webdriver.support.relative_locator import locate_with
driver.find_element(
locate_with(By.TAG_NAME, "input").below((By.ID, "username"))
)
|
Interactions
| Action |
Example |
| Click an Element |
# Correctly assigning the found element to a variable
button = driver.find_element(By.ID, "button_id")
# Click the button
button.click()
|
| Input Text |
# locate the element
element = driver.find_element(By.ID, "input_id")
# send the text
element.send_keys("Your text")
|
| Clear Text |
element.clear() |
| Submit a Form |
form = driver.find_element(By.ID, "form_id")
form.submit()
|
Waits
| Type |
Example |
| Implicit Wait |
driver.implicitly_wait(5) # Waits up to 5 seconds for elements to appear |
| Explicit Wait |
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, timeout=2)
element = wait.until(
EC.visibility_of_element_located((By.ID, "example"))
)
|
Headless Mode
| Task |
Example |
| Run Google Chrome in Headless Mode |
# headless mode
options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(options=options)
|
Handling Alerts
| Action |
Example |
| Switch to Alert |
alert = driver.switch_to.alert |
| Accept Alert |
alert.accept() |
| Dismiss Alert |
alert.dismiss() |
| Get Alert Text |
alert_text = alert.text
print(alert_text)
|
Handling Frames
| Action |
Example |
| Switch to a Frame |
driver.switch_to.frame(“frame_name_or_id”) |
| Switch to a Frame by Name or ID |
driver.switch_to.frame(“frame_name_or_id”) |
| Switch to a Frame by Index |
driver.switch_to.frame(0) |
| Switch to a Frame using a WebElement |
frame_element = driver.find_element(By.XPATH, "//iframe[@id='frame_id']")
driver.switch_to.frame(frame_element)
|
| Switch to Parent Frame |
driver.switch_to.parent_frame() |
| Switch to Default Content |
driver.switch_to.default_content() |
Handling Dropdowns
| Action |
Example |
| Select by Visible Text |
dropdown = Select(driver.find_element(By.ID, “dropdown_id”)); dropdown.select_by_visible_text(“Option Text”) |
| Select by Index |
dropdown.select_by_index(2) |
| Select by Value |
dropdown.select_by_value(“option_value”) |
Browser Navigation
| Action |
Example |
| Navigate to URL |
driver.get(“https://example.com”) |
| Back |
driver.back() |
| Forward |
driver.forward() |
| Refresh Page |
driver.refresh() |
| Close Current Tab or Window |
driver.close() |
| Quit Entire Session |
driver.quit() |
Browser Window Management
| Action |
Example |
| Get the Current Window Handle |
current_window = driver.current_window_handle |
| Get All Window Handles |
all_windows = driver.window_handles |
| Switch to a Specific Window |
# Get all window handles
handles = driver.window_handles
# Switch to the second window (index 1)
driver.switch_to.window(handles[1])
|
| Open a New Blank Tab and Switch to it |
driver.switch_to.new_window(WindowType.TAB) |
| Switching Windows or Tabs |
original_window_handle = driver.current_window_handle
driver.find_element(By.LINK_TEXT, "Open new window").click()
wait.until(EC.number_of_windows_to_be(2))
new_window_handle = (set(driver.window_handles) - {original_window_handle}).pop()
driver.switch_to.window(new_window_handle)
assert driver.current_window_handle == new_window_handle
|
| Fullscreen Window |
driver.fullscreen_window() |
| Minimize Window |
driver.minimize_window() |
| Maximize Window |
driver.maximize_window() |
| Get Window Size |
size = driver.get_window_size()
width1 = size.get("width")
height1 = size.get("height")
|
| Set Window Position |
driver.set_window_position(100, 200) |
Cookies
| Action |
Example |
| Add Cookie |
driver.add_cookie({“name”: “key”, “value”: “value”}) |
| Get All Cookies |
cookies = driver.get_cookies() |
| Delete Cookie |
driver.delete_cookie(“test_cookie”) |
| Delete All Cookie |
driver.delete_all_cookies() |
Taking Screenshot
| Type |
Example |
| Full Page |
driver.save_screenshot(“full_page_screenshot.png”) |
| WebElement Screenshot |
element = driver.find_element(By.ID, "element_id")
element.screenshot("element_screenshot.png")
|
Working with Files
| Task |
Method |
Example |
| Upload a File |
Send file path to input |
file_input = driver.find_element(By.ID, "file_upload_id")
# Replace with the actual locator
file_input.send_keys("/path/to/your/file.txt")
|
| Read Data from a Text File |
Read Entire File Content |
with open("example.txt", "r") as file:
content = file.read()
print("File Content:")
print(content)
|
| Read Data from a Text File |
Read File Line by Line |
with open("example.txt", "r") as file:
for line in file:
print("Line:", line.strip())
|
| Read Data from a Text File |
Use File Data in Selenium |
with open("test_data.txt", "r") as file:
data = file.readlines()
|
| Read Data from a CSV File |
Use `csv` module |
import csv
# Read the entire CSV file
with open("example.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print("Row:", row)
|
| Read Data from an Excel File |
Using openpyxl |
pip install openpyxl
from openpyxl import load_workbook
# Load the workbook
workbook = load_workbook("example.xlsx")
# Select the active worksheet
sheet = workbook.active
# Read all rows
for row in sheet.iter_rows(values_only=True):
print(row)
|
| Read Data from an Excel File |
Using pandas |
pip install pandas
import pandas as pd
# Load the Excel file
data = pd.read_excel("example.xlsx")
# Iterate over rows
for index, row in data.iterrows():
print(f"Row {index}: {row}")
|
JavaScript Execution
| Action |
Example |
| Execute JavaScript |
driver.execute_script(“JavaScript code here”) |
| Disable a Field (set the “disabled” attribute) |
driver.execute_script(“arguments[0].setAttribute(‘disabled’, ‘true’)”, field) |
| Enable a Field (remove the “disabled” attribute) |
driver.execute_script(“arguments[0].removeAttribute(‘disabled’)”, field) |
Selenium Grid
| Task |
Command |
| Start Hub |
java -jar selenium-server.jar hub |
| Start Node |
java -jar selenium-server.jar node –hub http://localhost:4444 |
| Server |
http://localhost:4444/ui |
Best Practices
- Use explicit waits over implicit waits for better performance.
- Handle exceptions to avoid flaky tests:
try:
element = driver.find_element(By.ID, "nonexistent_id")
except Exception as e:
print("Error:", e)
- Avoid `executable_path`.
- Keep locators clean and prefer CSS over XPath when possible.
- Use Page Object Model (POM) for large projects.
- Run tests in headless mode in CI/CD.
- Prefer `pytest` over `unittest` for flexibility.
- Always quit the WebDriver:
driver.quit()
We trust this Selenium with Python commands cheat sheet will be a valuable resource to support your testing journey!
Frequently Asked Questions (FAQs)
Do I still need to download WebDriver manually in Selenium 4?
No. Selenium 4+ includes Selenium Manager, which automatically handles browser drivers in most cases.
What is the best way to wait for elements in Selenium?
Use explicit waits (`WebDriverWait`). They are more reliable and efficient than implicit waits or hard sleeps.
Why are my old Selenium scripts not working?
Most likely due to:
- Deprecated methods like
find_element_by_*
- Outdated driver setup using
executable_path
- Changes introduced in Selenium 4 APIs