Turn your manual testers into automation experts! Request a DemoStart testRigor Free

Selenium with Python Cheat Sheet

Selenium is a popular browser automation framework used for web testing automation. This cheat sheet provides a quick reference to the most common Selenium commands when using Python, focusing on Selenium 4.x and the latest Selenium Grid.

Driver Initialization

To start, you need to import the required libraries and initialize the WebDriver for the
specific browser you are targeting.
from selenium import webdriver
Chrome driver = webdriver.Chrome(executable_path="path/to/chromedriver")
Firefox driver = webdriver.Firefox(executable_path="path/to/geckodriver")
Safari driver = webdriver.Safari(executable_path="path/to/safaridriver")
Edge driver = webdriver.Edge(executable_path="path/to/msedgedriver")

Locating Elements

By ID: driver.find_element_by_id("username")
By Name: driver.find_element_by_name("password")
By Class Name: driver.find_element_by_class_name("submit-btn")
By Tag Name: driver.find_element_by_tag_name("h1")
By CSS Selector: driver.find_element_by_css_selector("#login-form > div > input[type='submit']")
By XPath: driver.find_element_by_xpath("//input[@type='submit']")
By Link Text: driver.find_element_by_link_text("Sign Up")
By Partial Link Text: driver.find_element_by_partial_link_text("Sign")


  1. Test functions: Define test functions by prefixing their names with “test_”. Pytest
    will automatically discover and run these functions as test cases.
    def test_example_function():
      # Test code here
  2. Fixtures are used to set up and tear down resources, like test data or objects. They
    can be created using the @pytest.fixture decorator and are passed as function arguments to
    the test functions that need them.
    import pytest
      def example_fixture():
        # Set up code here
        # Tear down code here
      def test_example_function(example_fixture):
        # Test code here


  1. Test classes: Create test classes by inheriting from unittest.TestCase.
    import unittest
    class ExampleTestCase(unittest.TestCase):
  2. Test methods: Define test methods within the test classes by prefixing their names with
    class ExampleTestCase(unittest.TestCase):
      def test_example_method(self):
        # Test code here
  3. setUp and tearDown: These methods are used to set up and tear down resources for each
    test method. Override them in your test class as needed.
    class ExampleTestCase(unittest.TestCase):
      def setUp(self):
        # Set up code here
      def tearDown(self):
        # Tear down code here
      def test_example_method(self):
        # Test code here
  4. setUpClass and tearDownClass: These class methods are used to set up and tear down
    resources for the entire test class. Override them in your test class and use the
    @classmethod decorator.
    class ExampleTestCase(unittest.TestCase):
        def setUpClass(cls):
          # Set up code here
        def tearDownClass(cls):
          # Tear down code here
      def test_example_method(self):
        # Test code here

Working with Files

Upload a file:
file_input = driver.find_element_by_id("file-upload")
Read data from a text file:
with open("path/to/your/file.txt", "r") as file:
data = file.read()
Read data from a CSV file:
import csv
with open("path/to/your/file.csv", "r") as csvfile:
csv_reader = csv.reader(csvfile)
  for row in csv_reader:
Read data from an Excel file:
import openpyxl (install with pip install openpyxl)
workbook = openpyxl.load_workbook("path/to/your/file.xlsx")
worksheet = workbook.active
for row in worksheet.iter_rows():
  for cell in row:

Selenium Navigators

Navigate to a URL:
Refresh the page:
Navigate forward in browser history:
Navigate back in browser history:

Working with Windows

Get the current window handle:
Get all window handles:
Switch to a specific window:
Switch to the last opened window:
Close the current window:

Working with Frames

Switch to a frame by name or ID:
Switch to a frame by index:
driver.switch_to.frame(0) # Switch to the first frame by index
Switch to a frame using a WebElement:
frame_element = driver.find_element_by_id("frame_id")
Switch back to the main content:

Selenium Operations

Lauch a Webpage:
Click a button:
button = driver.find_element_by_id("button_id")
Accept an alert pop-up:
alert = driver.switch_to.alert
Print the page title:
Implicit wait:
driver.implicitly_wait(10) # Waits up to 10 seconds for elements to appear
Explicit wait:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "element_id")))
import time
time.sleep(5) # Pause the script for 5 seconds
Clear the input field text:
input_field = driver.find_element_by_id("input_field_id")
Disable a field (set the ‘disabled’ attribute):
field = driver.find_element_by_id("field_id")
driver.execute_script("arguments[0].setAttribute('disabled', true)", field)
Enable a field (remove the ‘disabled’ attribute):
field = driver.find_element_by_id("field_id")
driver.execute_script("arguments[0].removeAttribute('disabled')", field)

Selenium Grid

Start the hub:
java -jar selenium-server-standalone-x.y.z.jar -role hub
Start a node:
java -jar selenium-server-standalone-x.y.z.jar -role node -hub

Alternative: write tests without a single line of code

testRigor is an AI-driven, end-to-end testing solution that empowers QA professionals to create and maintain complex automated tests without requiring coding skills. This comprehensive system supports testing of various platforms, including web, mobile, and desktop applications, and is suitable for functional regression, accessibility, load, and performance testing. By leveraging plain English statements and an advanced AI engine, testRigor provides excellent scalability, minimal maintenance, and faster test execution, setting itself apart from coded automation tools such as Selenium.

Selenium test:

Same test in testRigor:

check if page contains "Welcome Peter"

Organizations that have adopted testRigor have experienced significant improvements in their software testing processes, with increased test coverage, reduced defect escape rates, and accelerated release cycles. The platform not only enhances QA teams and delivery processes but also eliminates the need for maintaining testing infrastructure. The unique approach of testRigor allows for seamless collaboration among team members and ensures tests remain valid even after underlying framework changes or refactoring. This superior choice in test automation provides numerous key benefits, including cost savings, improved communication, and detailed test results for seamless debugging.

Join the next wave of functional testing now.
A testRigor specialist will walk you through our platform with a custom demo.
Related Articles

SAP Concur Testing

Concur Technologies, now SAP Concur, is an American software-as-a-service (SaaS) company providing travel and expense management ...

Authorize.net Testing

You need a payment gateway in several scenarios, especially when you are running a business that requires secure, efficient, and ...

KYC Portal CLM Testing

KYC Portal CLM is an award-winning Client Lifecycle Management (CLM) platform designed to streamline and automate the Know Your ...