Selenium Cheat Sheet
Setting up Selenium:
# Install Selenium using pip
pip install selenium
# Download the appropriate WebDriver for your browser (e.g., ChromeDriver for Chrome)
# Place the WebDriver executable in your system's PATH
Importing Selenium:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
Initializing the WebDriver:
# For Chrome
driver = webdriver.Chrome()
# For Firefox
driver = webdriver.Firefox()
# For Edge
driver = webdriver.Edge()
# For Safari (on macOS)
driver = webdriver.Safari()
Interacting with Elements:
# Navigating to a URL
driver.get("https://www.example.com")
# Finding elements
element = driver.find_element(By.ID, "element_id")
elements = driver.find_elements(By.CLASS_NAME, "element_class")
# Clicking an element
element.click()
# Sending keys to an input element
element.send_keys("Text")
# Pressing special keys
element.send_keys(Keys.ENTER)
# Getting element text
text = element.text
# Waiting for an element to be visible
wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "element_selector")))
Working with Windows and Frames:
# Switching to a new window
driver.switch_to.window(driver.window_handles[1])
# Switching to a frame by index
driver.switch_to.frame(0)
# Switching to a frame by name or ID
driver.switch_to.frame("frame_name")
# Switching to the default content
driver.switch_to.default_content()
Handling Alerts:
# Switching to an alert
alert = driver.switch_to.alert
# Accepting an alert
alert.accept()
# Dismissing an alert
alert.dismiss()
# Getting the alert text
text = alert.text
Performing Actions:
# Creating an ActionChains object
actions = webdriver.ActionChains(driver)
# Performing a series of actions
actions.move_to_element(element1)
actions.click()
actions.move_to_element(element2)
actions.click()
actions.perform()
Capturing Screenshots:
# Capturing a screenshot
driver.save_screenshot("screenshot.png")
Closing the WebDriver:
# Closing the current window
driver.close()
# Quitting the WebDriver
driver.quit()