0% found this document useful (0 votes)
4 views

Python Selenium Cheat Sheet (1)

The document is a comprehensive cheat sheet for using Python Selenium, covering topics from installation to advanced techniques. It includes code examples and descriptions for browser setup, element interactions, waits, navigation, handling alerts, and more. Best practices and tips for effective Selenium usage are also provided.

Uploaded by

arw1362
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Selenium Cheat Sheet (1)

The document is a comprehensive cheat sheet for using Python Selenium, covering topics from installation to advanced techniques. It includes code examples and descriptions for browser setup, element interactions, waits, navigation, handling alerts, and more. Best practices and tips for effective Selenium usage are also provided.

Uploaded by

arw1362
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Python Selenium Complete Cheat Sheet

Beginner to Advanced | With Code Examples & Descriptions

1. Introduction & Installation

2. Browser Setup & Opening Pages

3. Element Locators & Finding Elements

4. Element Interactions (click, type, clear)

5. Working with Forms & Dropdowns

6. Waits (Implicit & Explicit)

7. Navigations (back, forward, refresh)

8. Handling Multiple Windows & Tabs

9. Handling Alerts & Popups

10. Taking Screenshots

11. Working with Cookies

12. Executing JavaScript

13. Frames & iFrames

14. Advanced User Actions

15. Handling File Uploads & Downloads

16. Exception Handling in Selenium

17. Useful Tips & Best Practices

1. Introduction & Installation


Selenium is a popular Python library to automate web browsers for testing or
scraping.
It requires a WebDriver for your browser (e.g., ChromeDriver for Chrome).

Install Selenium using pip:

pip install selenium


Python Selenium Complete Cheat Sheet
Beginner to Advanced | With Code Examples & Descriptions

Download WebDriver:
- ChromeDriver: https://sites.google.com/chromium.org/driver/
- GeckoDriver: https://github.com/mozilla/geckodriver/releases

Add the driver executable to your system PATH or specify its location in code.

2. Browser Setup & Opening Pages


Create a browser instance and open a webpage.

Example:

from selenium import webdriver

# Launch Chrome browser (make sure chromedriver is in PATH)


driver = webdriver.Chrome()

# Open a webpage
driver.get("https://www.google.com")

# Close the browser


driver.quit()

3. Element Locators & Finding Elements


Locate elements using multiple strategies:
- By ID
- By Name
- By XPath
- By CSS Selector
- By Class Name
- By Tag Name
- By Link Text
- By Partial Link Text

Example:

# Find element by ID
Python Selenium Complete Cheat Sheet
Beginner to Advanced | With Code Examples & Descriptions

search_box = driver.find_element("id", "lst-ib")

# Find element by name


search_box = driver.find_element("name", "q")

# Find element by XPath


search_box = driver.find_element("xpath", "//input[@name='q']")

# Find multiple elements by class name


links = driver.find_elements("class name", "r")

4. Element Interactions (click, type, clear)


Interact with elements like buttons and input fields.

Example:

search_box = driver.find_element("name", "q")

# Type text into search box


search_box.send_keys("Selenium Python")

# Clear the input field


search_box.clear()

# Click a button or link


search_box.submit() # Submit form

5. Working with Forms & Dropdowns


Handle forms and select options in dropdown menus.

Example:

from selenium.webdriver.support.ui import Select

select = Select(driver.find_element("id", "dropdown_id"))

# Select by visible text


select.select_by_visible_text("Option 1")
Python Selenium Complete Cheat Sheet
Beginner to Advanced | With Code Examples & Descriptions

# Select by value attribute


select.select_by_value("option1")

# Select by index (0-based)


select.select_by_index(1)

6. Waits (Implicit & Explicit)


Wait for elements to load before interacting.

Implicit wait:

driver.implicitly_wait(10) # waits up to 10 seconds

Explicit wait (recommended):

from selenium.webdriver.common.by import By


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

wait = WebDriverWait(driver, 10)


element = wait.until(EC.presence_of_element_located((By.ID, "element_id")))

7. Navigations (back, forward, refresh)


Navigate browser history.

Example:

driver.back() # Go back
driver.forward() # Go forward
driver.refresh() # Refresh current page

8. Handling Multiple Windows & Tabs


Switch between browser tabs or windows.

Example:
Python Selenium Complete Cheat Sheet
Beginner to Advanced | With Code Examples & Descriptions

# Get current window handle


main_window = driver.current_window_handle

# Get all window handles


all_windows = driver.window_handles

# Switch to new window/tab


driver.switch_to.window(all_windows[1])

9. Handling Alerts & Popups


Handle JavaScript alerts, confirms, and prompts.

Example:

alert = driver.switch_to.alert

# Accept alert
alert.accept()

# Dismiss alert
alert.dismiss()

# Get alert text


print(alert.text)

# Send text to prompt alert


alert.send_keys("Some text")

10. Taking Screenshots


Capture screenshot of current page.

Example:

driver.save_screenshot("screenshot.png")

11. Working with Cookies


Get, add, and delete cookies.
Python Selenium Complete Cheat Sheet
Beginner to Advanced | With Code Examples & Descriptions

Example:

# Get all cookies


cookies = driver.get_cookies()

# Add cookie
driver.add_cookie({"name": "foo", "value": "bar"})

# Delete cookie
driver.delete_cookie("foo")

# Delete all cookies


driver.delete_all_cookies()

12. Executing JavaScript


Run JavaScript in browser context.

Example:

title = driver.execute_script("return document.title;")


print(title)

13. Frames & iFrames


Switch to iframe and back.

Example:

# Switch to iframe by name or id


driver.switch_to.frame("frame_name")

# Switch back to main content


driver.switch_to.default_content()

14. Advanced User Actions


Perform advanced actions like hover and drag-drop.
Python Selenium Complete Cheat Sheet
Beginner to Advanced | With Code Examples & Descriptions

Example:

from selenium.webdriver import ActionChains

actions = ActionChains(driver)
element = driver.find_element("id", "element_id")

# Hover over element


actions.move_to_element(element).perform()

# Drag and drop


source = driver.find_element("id", "source")
target = driver.find_element("id", "target")
actions.click_and_hold(source).move_to_element(target).release().perform()

15. Handling File Uploads & Downloads


Handle file uploads by sending file path to input.

Example:

file_input = driver.find_element("id", "upload")


file_input.send_keys("/path/to/file.txt")

Note: File downloads usually need browser profile adjustments.

16. Exception Handling in Selenium


Handle common Selenium exceptions to avoid crashes.

Example:

from selenium.common.exceptions import NoSuchElementException, TimeoutException

try:
element = driver.find_element("id", "does_not_exist")
except NoSuchElementException:
print("Element not found")
except TimeoutException:
print("Timed out waiting for element")
Python Selenium Complete Cheat Sheet
Beginner to Advanced | With Code Examples & Descriptions

17. Useful Tips & Best Practices


- Use explicit waits over implicit waits for reliability.
- Always quit() the driver after tests to free resources.
- Use Page Object Model for large projects (separate locators and logic).
- Use headless mode for running tests without UI.

You might also like