Selenium with Python Cheat
Sheet
Artem Golubev
April 18, 2023
-Resources-
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 fo
specific browser you are targeting.
from selenium import webdriver
Chrome driver = webdriver.Chrome(executable_path="path/to/chromedr
Firefox driver = webdriver.Firefox(executable_path="path/to/geckodr
Safari driver = webdriver.Safari(executable_path="path/to/safaridr
Edge driver = webdriver.Edge(executable_path="path/to/msedgedriv
Locating Elements
By ID: driver.find_element_by_id("username")
By Name: driver.find_element_by_name("password")
By Class driver.find_element_by_class_name("submit-btn")
Name:
By Tag Name: driver.find_element_by_tag_name("h1")
By CSS driver.find_element_by_css_selector("#login-form > div >
Selector: 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 driver.find_element_by_partial_link_text("Sign")
Text:
Pytest
1. Test functions: Define test functions by prefixing their names with “test_”. Py
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 object
can be created using the @pytest.fixture decorator and are passed as func
arguments to
the test functions that need them.
import pytest
@pytest.fixture
def example_fixture():
# Set up code here
yield
# Tear down code here
def test_example_function(example_fixture):
# Test code here
Unittest
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
with
“test_”.
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 reso
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
down
resources for the entire test class. Override them in your test class and use t
@classmethod decorator.
class ExampleTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Set up code here
@classmethod
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")
file_input.send_keys("path/to/your/file.txt")
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:
print(row)
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:
print(cell.value)
Selenium Navigators
Navigate to a URL:
driver.get("https://www.example.com")
Refresh the page:
driver.refresh()
Navigate forward in browser history:
driver.forward()
Navigate back in browser history:
driver.back()
Working with Windows
Get the current window handle:
driver.current_window_handle
Get all window handles:
driver.window_handles
Switch to a specific window:
driver.switch_to.window("window_handle")
Switch to the last opened window:
driver.switch_to.window(driver.window_handles[-1])
Close the current window:
driver.close()
Working with Frames
Switch to a frame by name or ID:
driver.switch_to.frame("frame_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")
driver.switch_to.frame(frame_element)
Switch back to the main content:
driver.switch_to.default_content()
Selenium Operations
Lauch a Webpage:
driver.get("https://www.example.com")
Click a button:
button = driver.find_element_by_id("button_id")
button.click()
Accept an alert pop-up:
alert = driver.switch_to.alert
alert.accept()
Print the page title:
print(driver.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, "eleme
Sleep:
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")
input_field.clear()
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
Server:
http://localhost:4444/ui/index.html
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:
login
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.
Request a Demo
Start testRigor Free
Related Articles
-Resources- Software Testing
SAP Concur Testing
Concur Technologies, now SAP Concur, is an American software-as-a-service
(SaaS) company providing travel and expense management ...
Hari Mahesh
February 22, 2024
-Resources- Software Testing
Authorize.net Testing
You need a payment gateway in several scenarios, especially when you are
running a business that requires secure, efficient, and ...
Anushree Chatterjee
February 22, 2024
-Resources- Software Testing
KYC Portal CLM Testing
KYC Portal CLM is an award-winning Client Lifecycle Management (CLM)
platform designed to streamline and automate the Know Your ...
Hari Mahesh
February 16, 2024
Automate tests with plain English using Generative AI. Reduce QA overhead,
increase coverage, efficiency and scalability.
Get Our Newsletter
We will send monthly testRigor updates on new features, upcoming events and links to
recordings.
Email*
Email*
Join
Product Company Resources & Learning
Pricing About testRigor Certification: AI-
driven Test Automation
Why testRigor Mission
FAQ
Features Careers
Documentation
Benefits Contact Us
Language Documentation
AI in Software Testing Become Partner
How-to Articles
Generative AI in Software Blog
Testing Releases
Prompt Engineering in Events
Software Testing
Software Testing
AI Agents in Software
Testing End-To-End Testing
AI Features Testing Framework Testing
AI-Based Self-Healing ERP Testing
How Does It All Work? Selenium self-healing
Selenium Alternative Common Sense in Test
Automation
Appium Alternative
Enterprise Estimation
Cypress Alternative Calculator
Sign Up ROI of Nocode Test
Automation Calculator
Login
Test Automation Blueprint
Public Tests
Terms and conditions
Privacy policy
© 2024 testRigor. All rights reserved.