Selenium Python Detailed Cheat Sheet
Installation & Setup
Install Selenium via pip:
pip install selenium
Download ChromeDriver matching your Chrome version from the official site.
Specifying ChromeDriver Path
Windows:
driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe')
macOS/Linux:
driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver')
Or add ChromeDriver to your PATH or symlink into /usr/local/bin.
Browser Options & Capabilities
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--headless') # run headless
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=options)
Locators & Element Interaction
driver.find_element(By.ID, 'id')
driver.find_element(By.NAME, 'name')
driver.find_element(By.CLASS_NAME, 'class')
driver.find_element(By.XPATH, '//tag[@attr]')
driver.find_element(By.CSS_SELECTOR, 'css')
element.click()
element.send_keys('text')
Waits & Synchronization
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'id')))
driver.implicitly_wait(5)
Screenshots & Logs
driver.save_screenshot('screen.png')
print(driver.get_log('browser'))
Advanced Usage
Remote WebDriver / Selenium Grid:
from selenium import webdriver
driver = webdriver.Remote(
command_executor='http://grid:4444/wd/hub',
desired_capabilities=DesiredCapabilities.CHROME
)
Selenium Python Detailed Cheat Sheet
Advanced Usage
Custom Profiles & Extensions:
options.add_extension('path/to/extension.crx')
options.add_argument('--user-data-dir=/path/to/profile')
Teardown
driver.quit()
Best Practices
Use explicit waits over sleeps, modularize locators, handle exceptions gracefully.