Python Basics for Selenium
Python Basics for Selenium covers the fundamental Python programming concepts required to create, understand, execute, and maintain Selenium WebDriver automation scripts. Selenium provides browser automation capabilities, while Python provides the programming language used to write automation logic, test cases, reusable functions, validations, and automation frameworks.
Before working extensively with Selenium WebDriver, a learner should understand Python variables, data types, operators, conditions, loops, functions, collections, strings, exception handling, modules, classes, objects, file handling, and basic Object-Oriented Programming concepts.
JustAcademy's Selenium training curriculum includes programming fundamentals such as variables, loops, conditions, functions, Object-Oriented Programming, exception handling, collections, and file handling as part of the programming foundation for automation testing.
Explore JustAcademy Selenium Training | Register for Course Demo
1. What is Python?
Python is a high-level, interpreted, general-purpose programming language known for its simple syntax and readability. In automation testing, Python can be used with Selenium WebDriver to create scripts that open browsers, navigate websites, locate elements, enter data, click buttons, validate results, handle browser interactions, and generate reusable automation solutions.
Example
print("Hello Selenium")
print("Python is used for automation testing")
Output
Hello Selenium
Python is used for automation testing
2. Why Learn Python for Selenium?
Selenium WebDriver needs a programming language to define the actions that should be performed against a web application. Python provides a concise syntax and a large ecosystem of libraries that make it suitable for automation scripting.
- Easy-to-read syntax
- Less boilerplate code
- Supports Object-Oriented Programming
- Supports functions and reusable modules
- Provides powerful collection data types
- Provides exception handling
- Works with Selenium WebDriver
- Can be integrated with testing frameworks such as pytest
- Supports file and data processing
- Useful for building maintainable automation frameworks
3. Python and Selenium Relationship
Python
↓
Programming Logic
↓
Selenium WebDriver
↓
Browser Driver
↓
Chrome / Firefox / Edge
↓
Web Application
↓
Test Result
Python controls the automation logic, while Selenium WebDriver communicates with the browser and performs browser actions.
4. Installing Python
Python should be installed before creating Python-based Selenium scripts. After installation, verify the Python version from the command line.
python --version
On some systems, the following command may also be used:
python3 --version
5. Installing Selenium
The Selenium package can be installed using pip.
pip install selenium
After installation, Selenium can be imported into a Python program.
from selenium import webdriver
6. First Python Selenium Program
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.google.com")
print(driver.title)
driver.quit()
Explanation
- webdriver imports Selenium's WebDriver functionality.
- webdriver.Chrome() creates a Chrome browser session.
- driver.get() opens a URL.
- driver.title retrieves the current page title.
- driver.quit() closes the browser session.
7. Python Variables
A variable is a name used to store a value. Selenium scripts frequently use variables for URLs, usernames, passwords, locators, test data, WebElements, browser objects, and expected results.
browser_name = "Chrome"
username = "admin"
password = "admin123"
timeout = 10
Using Variables in Selenium
url = "https://example.com"
driver.get(url)
8. Rules for Python Variable Names
- Variable names can contain letters, numbers, and underscores.
- A variable name cannot start with a number.
- Python variable names are case-sensitive.
- Keywords should not be used as variable names.
- Use meaningful names in automation scripts.
username = "admin"
login_url = "https://example.com/login"
max_wait_time = 10
9. Python Data Types
Python provides different built-in data types for storing different kinds of values.
| Data Type | Example | Automation Usage |
| str | "Selenium" | URLs, usernames, messages |
| int | 10 | Timeouts, counts, indexes |
| float | 10.5 | Numeric test data |
| bool | True | Validation results |
| list | ["Chrome","Firefox"] | Multiple test values |
| tuple | ("id","username") | Immutable locator data |
| set | {"QA","Automation"} | Unique values |
| dict | {"username":"admin"} | Structured test data |
| None | None | Empty or unavailable values |
10. Strings in Python
Strings represent text and are heavily used in Selenium automation.
username = "admin"
message = "Login Successful"
url = "https://example.com"
String Methods
text = " Login Successful "
print(text.strip())
print(text.lower())
print(text.upper())
print(text.replace("Successful", "Completed"))
Why Strings Matter in Selenium
- URLs are strings.
- Element IDs are strings.
- CSS selectors are strings.
- XPath expressions are strings.
- User input is usually represented as strings.
- Expected messages are strings.
11. String Concatenation
String concatenation combines multiple strings.
first_name = "John"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name)
Using f-Strings
username = "admin"
message = f"Welcome {username}"
print(message)
F-strings are particularly useful when generating dynamic test data or messages.
12. Numbers in Python
Integers and floating-point numbers are commonly used for counts, timeout values, prices, quantities, and other test data.
timeout = 10
product_quantity = 3
product_price = 499.50
13. Boolean Values
Boolean values represent either True or False. Selenium methods frequently return Boolean values.
is_logged_in = True
is_admin = False
print(is_logged_in)
Selenium Example
button = driver.find_element(By.ID, "submit")
print(button.is_enabled())
print(button.is_displayed())
print(button.is_selected())
14. Python Operators
Operators are symbols or keywords used to perform operations on values.
| Category | Operators |
| Arithmetic | +, -, *, /, %, //, ** |
| Comparison | ==, !=, >, <, >=, <= |
| Logical | and, or, not |
| Assignment | =, +=, -=, *=, /= |
| Membership | in, not in |
| Identity | is, is not |
15. Comparison Operators
Comparison operators are important when validating expected and actual values.
expected_title = "Google"
actual_title = driver.title
if actual_title == expected_title:
print("Title matched")
else:
print("Title did not match")
16. Conditional Statements
Conditional statements allow an automation script to make decisions based on conditions.
username = "admin"
if username == "admin":
print("Valid user")
else:
print("Invalid user")
Selenium Example
if driver.find_element(By.ID, "logout").is_displayed():
print("User is logged in")
else:
print("User is not logged in")
17. if, elif and else
status = "success"
if status == "success":
print("Test Passed")
elif status == "failed":
print("Test Failed")
else:
print("Unknown Status")
18. Nested Conditions
One condition can be placed inside another condition.
username = "admin"
password = "admin123"
if username == "admin":
if password == "admin123":
print("Login credentials are valid")
else:
print("Invalid password")
else:
print("Invalid username")
19. Python Lists
A list stores multiple values in an ordered and mutable collection.
browsers = ["Chrome", "Firefox", "Edge"]
print(browsers[0])
print(browsers[1])
Selenium Example
urls = [
"https://example.com/login",
"https://example.com/products",
"https://example.com/contact"
]
for url in urls:
driver.get(url)
print(driver.title)
20. List Methods
browsers = ["Chrome", "Firefox"]
browsers.append("Edge")
browsers.remove("Firefox")
print(browsers)
Lists are useful for storing test cases, URLs, usernames, products, expected values, and multiple WebElements.
21. Python Tuples
A tuple is an ordered collection that cannot be modified after creation.
locator = ("id", "username")
print(locator[0])
print(locator[1])
Locator information is commonly represented as a tuple when using Selenium's Python APIs.
from selenium.webdriver.common.by import By
locator = (By.ID, "username")
element = driver.find_element(*locator)
22. Python Dictionaries
A dictionary stores data as key-value pairs. Dictionaries are extremely useful for structured test data.
user = {
"username": "admin",
"password": "admin123",
"role": "tester"
}
print(user["username"])
print(user["password"])
Selenium Test Data Example
login_data = {
"username": "admin",
"password": "admin123"
}
driver.find_element(By.ID, "username").send_keys(login_data["username"])
driver.find_element(By.ID, "password").send_keys(login_data["password"])
23. Python Sets
A set stores unique values.
browsers = {"Chrome", "Firefox", "Edge"}
print(browsers)
Sets can be useful when duplicate test values need to be removed or when comparing collections of unique values.
24. for Loop
A for loop is used to repeat an operation for each item in a sequence.
browsers = ["Chrome", "Firefox", "Edge"]
for browser in browsers:
print(browser)
Selenium Example
links = driver.find_elements(By.TAG_NAME, "a")
for link in links:
print(link.text)
25. while Loop
A while loop repeatedly executes a block of code while a condition remains true.
count = 1
while count <= 3:
print(count)
count += 1
While loops should be used carefully in automation so that a test does not enter an unintended infinite loop.
26. break Statement
The break statement stops a loop immediately.
for browser in ["Chrome", "Firefox", "Edge"]:
if browser == "Firefox":
break
print(browser)
27. continue Statement
The continue statement skips the current iteration and moves to the next iteration.
for number in range(1, 6):
if number == 3:
continue
print(number)
28. range() Function
The range() function generates a sequence of numbers and is commonly used with loops.
for i in range(5):
print(i)
Selenium Example
for i in range(3):
driver.get("https://example.com")
print("Iteration:", i + 1)
29. Python Functions
A function is a reusable block of code that performs a specific task. Functions are essential for creating maintainable Selenium automation scripts.
def login():
print("Performing login")
login()
30. Functions with Parameters
def login(username, password):
print("Username:", username)
print("Password:", password)
login("admin", "admin123")
Selenium Example
def login(driver, username, password):
driver.find_element(By.ID, "username").send_keys(username)
driver.find_element(By.ID, "password").send_keys(password)
driver.find_element(By.ID, "login").click()
31. Return Statement
The return statement sends a value back from a function.
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Selenium Example
def get_page_title(driver):
return driver.title
title = get_page_title(driver)
print(title)
32. Default Function Arguments
def open_page(driver, url="https://example.com"):
driver.get(url)
open_page(driver)
33. *args and **kwargs Basics
Python allows functions to receive a variable number of positional or keyword arguments.
def print_values(*args):
for value in args:
print(value)
print_values("Chrome", "Firefox", "Edge")
def test_user(**kwargs):
print(kwargs["username"])
print(kwargs["role"])
test_user(username="admin", role="tester")
34. Scope of Variables
Variables can have local or global scope.
browser = "Chrome"
def show_browser():
browser_name = "Firefox"
print(browser_name)
show_browser()
print(browser)
In automation projects, local variables are generally preferred when data does not need to be shared globally.
35. Python Modules
A module is a Python file containing reusable code such as functions, classes, or variables.
Example
# browser_utils.py
def open_application(driver, url):
driver.get(url)
The function can then be imported into another file.
from browser_utils import open_application
36. Import Statement
Python's import statement allows code from modules and packages to be used in another program.
import time
time.sleep(2)
Selenium Imports
from selenium import webdriver
from selenium.webdriver.common.by import By
37. Exception Handling
Automation scripts interact with external systems such as browsers and web applications, so failures can occur during execution. Python exception handling allows scripts to handle expected runtime problems without immediately terminating the entire program.
try:
number = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
38. try, except, else and finally
try:
print("Executing test")
except Exception as e:
print("Error:", e)
else:
print("Test completed successfully")
finally:
print("Cleanup completed")
39. Selenium Exception Handling
from selenium.common.exceptions import NoSuchElementException
try:
element = driver.find_element(By.ID, "username")
element.send_keys("admin")
except NoSuchElementException:
print("Username field was not found")
finally:
driver.quit()
Exception handling should be used thoughtfully. It should not hide genuine test failures or replace proper synchronization and validation.
40. Common Selenium Exceptions
| Exception | Typical Meaning |
| NoSuchElementException | Element could not be located |
| TimeoutException | Wait condition did not succeed within the timeout |
| ElementNotInteractableException | Element cannot currently be interacted with |
| ElementClickInterceptedException | Another element is preventing the click |
| StaleElementReferenceException | Previously located element is no longer attached to the current DOM |
| InvalidSelectorException | Locator syntax is invalid |
| NoSuchWindowException | Referenced browser window is unavailable |
| NoSuchFrameException | Referenced frame is unavailable |
41. Object-Oriented Programming Basics
Object-Oriented Programming, commonly called OOP, organizes software using classes and objects. OOP becomes particularly important when Selenium projects grow and Page Object Model or reusable automation frameworks are introduced.
The major OOP concepts include:
- Class
- Object
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
42. Class in Python
A class is a blueprint for creating objects.
class LoginPage:
def login(self):
print("Login operation")
43. Object in Python
An object is an instance of a class.
class Browser:
def open(self):
print("Opening browser")
browser = Browser()
browser.open()
44. __init__() Constructor
The __init__() method is commonly used to initialize object data.
class LoginPage:
def __init__(self, driver):
self.driver = driver
This pattern is widely used in Selenium Page Object Model classes.
45. self Keyword
The self keyword refers to the current object. It allows class methods to access instance variables and other methods.
class LoginPage:
def __init__(self, driver):
self.driver = driver
def open(self, url):
self.driver.get(url)
46. Encapsulation
Encapsulation means keeping related data and behavior together inside a class and controlling how that data is accessed.
Selenium Example
class LoginPage:
def __init__(self, driver):
self.driver = driver
def enter_username(self, username):
self.driver.find_element(By.ID, "username").send_keys(username)
def enter_password(self, password):
self.driver.find_element(By.ID, "password").send_keys(password)
def click_login(self):
self.driver.find_element(By.ID, "login").click()
47. Inheritance
Inheritance allows one class to reuse functionality from another class.
class BasePage:
def open(self, driver, url):
driver.get(url)
class LoginPage(BasePage):
def login(self):
print("Login operation")
Base classes are frequently used to store reusable Selenium operations in automation frameworks.
48. Polymorphism
Polymorphism allows different classes or objects to provide their own implementation of a common operation.
class ChromeBrowser:
def open(self):
print("Opening Chrome")
class FirefoxBrowser:
def open(self):
print("Opening Firefox")
browsers = [ChromeBrowser(), FirefoxBrowser()]
for browser in browsers:
browser.open()
49. Abstraction
Abstraction means exposing the necessary functionality while hiding unnecessary implementation details.
In Selenium frameworks, a test can call a method such as login() without needing to know every low-level interaction performed by that method.
50. Python Lists with Selenium WebElements
The find_elements() method returns multiple matching elements, which can be processed using Python lists and loops.
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://example.com")
links = driver.find_elements(By.TAG_NAME, "a")
for link in links:
print(link.text)
driver.quit()
51. Working with WebElement Variables
A Selenium WebElement can be stored in a Python variable and then reused.
username_field = driver.find_element(By.ID, "username")
username_field.clear()
username_field.send_keys("admin")
52. Common Selenium WebElement Operations
| Operation | Purpose |
| click() | Clicks an element |
| send_keys() | Enters keyboard input |
| clear() | Clears an input field |
| text | Reads visible text |
| get_attribute() | Reads an HTML attribute |
| is_displayed() | Checks whether an element is displayed |
| is_enabled() | Checks whether an element is enabled |
| is_selected() | Checks whether an option/control is selected |
53. Python Comments
Comments explain code and improve maintainability.
# Open the login page
driver.get("https://example.com/login")
# Enter username
driver.find_element(By.ID, "username").send_keys("admin")
54. Single-Line and Multi-Line Comments
# This is a single-line comment
"""
This is a multi-line
documentation string example.
"""
Clear comments are useful for explaining complex automation logic, but unnecessary comments should be avoided.
55. Python Indentation
Indentation is an essential part of Python syntax. Python uses indentation to define code blocks.
if True:
print("This line belongs to the if block")
Incorrect indentation can cause an IndentationError.
56. Python Boolean Conditions in Selenium
login_button = driver.find_element(By.ID, "login")
if login_button.is_enabled():
login_button.click()
else:
print("Login button is disabled")
57. Python Input Function
The input() function reads information from the user.
username = input("Enter username: ")
print(username)
Although interactive input is not normally used in automated CI tests, the concept is useful for understanding Python basics.
58. Type Conversion
Python provides functions such as int(), float(), str(), and bool() to convert values between data types.
quantity = "5"
quantity_number = int(quantity)
print(quantity_number + 2)
Selenium Test Data Example
price_text = "499"
price = int(price_text)
print(price + 100)
59. len() Function
The len() function returns the number of items in a collection or characters in a string.
username = "admin"
print(len(username))
Selenium Example
links = driver.find_elements(By.TAG_NAME, "a")
print("Number of links:", len(links))
60. Membership Operators
The in and not in operators are useful for checking whether a value exists in a collection or string.
message = "Login Successful"
if "Successful" in message:
print("Login validation passed")
61. Working with Files
Automation projects frequently need to read or write test data, configuration information, logs, or generated results.
Writing to a File
with open("test_result.txt", "w") as file:
file.write("Login Test Passed")
Reading a File
with open("test_result.txt", "r") as file:
content = file.read()
print(content)
62. The with Statement
The with statement manages resources automatically and is commonly used for file operations.
with open("data.txt", "r") as file:
data = file.read()
Using with is generally preferable to manually opening and closing files.
63. Working with CSV Test Data
CSV files are commonly used for data-driven testing.
import csv
with open("users.csv", newline="") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["username"])
print(row["password"])
64. Python Packages
A package is a collection of Python modules organized into a directory structure. Selenium itself is installed as a Python package.
pip install selenium
Other automation projects may also use packages for testing, reporting, data handling, configuration, and API interaction.
65. pip Basics
pip is Python's package installation tool.
pip install selenium
pip show selenium
pip list
pip uninstall selenium
66. Virtual Environment
A virtual environment isolates project dependencies so that different Python projects can use different package versions.
Create a Virtual Environment
python -m venv venv
Windows Activation
venv\Scripts\activate
Install Selenium
pip install selenium
67. Python Naming Conventions for Selenium
Readable naming is important in automation projects because test scripts are frequently maintained by multiple testers and developers.
driver
login_button
username_field
password_field
expected_title
actual_title
product_list
test_data
Use descriptive names rather than unclear names such as x, y, a, or temp for important automation objects.
68. Basic Selenium Locator Variables
username_locator = (By.ID, "username")
password_locator = (By.ID, "password")
login_locator = (By.ID, "login")
Keeping locators in variables or Page Object classes can improve readability and maintainability.
69. Python Lambda Functions
A lambda is a small anonymous function.
square = lambda x: x * x
print(square(5))
Selenium Example
from selenium.webdriver.support.ui import WebDriverWait
WebDriverWait(driver, 10).until(
lambda d: d.find_element(By.ID, "status").text == "Completed"
)
70. List Comprehension
List comprehension provides a compact way to create lists.
numbers = [1, 2, 3, 4, 5]
squares = [number * number for number in numbers]
print(squares)
Selenium Example
links = driver.find_elements(By.TAG_NAME, "a")
link_texts = [link.text for link in links]
print(link_texts)
71. Enumerate Function
enumerate() provides both an index and an item while iterating.
browsers = ["Chrome", "Firefox", "Edge"]
for index, browser in enumerate(browsers, start=1):
print(index, browser)
72. Zip Function
zip() allows multiple sequences to be iterated together.
usernames = ["admin", "tester"]
passwords = ["admin123", "test123"]
for username, password in zip(usernames, passwords):
print(username, password)
This can be useful when pairing test data values.
73. Assertions Basics
Assertions are used to verify that an actual value matches an expected condition. Python provides a built-in assert statement.
expected_title = "Example Domain"
assert driver.title == expected_title
In larger test frameworks, framework-specific assertion features are commonly used to produce structured test results.
74. Python Selenium Login Example
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get("https://example.com/login")
driver.find_element(By.ID, "username").send_keys("admin")
driver.find_element(By.ID, "password").send_keys("admin123")
driver.find_element(By.ID, "login").click()
print("Login operation completed")
finally:
driver.quit()
75. Python Selenium Search Example
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
search_box = driver.find_element(By.NAME, "q")
search_box.send_keys("Selenium Python")
search_box.submit()
print(driver.title)
finally:
driver.quit()
76. Python Selenium Form Automation Example
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get("https://example.com/register")
driver.find_element(By.ID, "firstName").send_keys("John")
driver.find_element(By.ID, "lastName").send_keys("Smith")
driver.find_element(By.ID, "email").send_keys("[email protected]")
driver.find_element(By.ID, "password").send_keys("Password123")
driver.find_element(By.ID, "register").click()
finally:
driver.quit()
77. Python Selenium with Explicit Wait
Dynamic websites may not make an element immediately ready for interaction. Explicit waits allow Selenium to wait for a specific condition.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
username = wait.until(
EC.visibility_of_element_located((By.ID, "username"))
)
username.send_keys("admin")
78. Python Selenium Page Object Model Basics
Page Object Model, or POM, is a design approach in which web page behavior and locators are organized inside page classes.
from selenium.webdriver.common.by import By
class LoginPage:
def __init__(self, driver):
self.driver = driver
username = (By.ID, "username")
password = (By.ID, "password")
login_button = (By.ID, "login")
def login(self, username, password):
self.driver.find_element(*self.username).send_keys(username)
self.driver.find_element(*self.password).send_keys(password)
self.driver.find_element(*self.login_button).click()
79. Base Page Concept
A BasePage class can contain common browser operations that are shared by multiple page classes.
class BasePage:
def __init__(self, driver):
self.driver = driver
def open(self, url):
self.driver.get(url)
def get_title(self):
return self.driver.title
80. Reusable Login Utility
def login(driver, username, password):
driver.find_element(By.ID, "username").clear()
driver.find_element(By.ID, "username").send_keys(username)
driver.find_element(By.ID, "password").clear()
driver.find_element(By.ID, "password").send_keys(password)
driver.find_element(By.ID, "login").click()
Reusable functions reduce duplicated automation code and make maintenance easier.
81. Python Data-Driven Selenium Concept
Data-driven automation separates test logic from test data. Python collections or external files can supply multiple sets of test data.
users = [
{"username": "admin", "password": "admin123"},
{"username": "tester", "password": "test123"},
{"username": "user", "password": "user123"}
]
for user in users:
print(user["username"])
print(user["password"])
82. Python Logging Basics
Logging is useful for understanding what an automation script is doing during execution.
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Starting Selenium test")
logging.info("Opening login page")
Why Logging Helps
- Tracks test execution.
- Helps investigate failures.
- Provides useful debugging information.
- Helps understand framework execution flow.
83. Python Date and Time Basics
Date and time values are often required when testing booking systems, reports, transactions, schedules, and date-based workflows.
from datetime import datetime
current_time = datetime.now()
print(current_time)
84. Python Regular Expressions Basics
Regular expressions can be useful for validating or extracting structured text such as emails, order IDs, phone numbers, and generated values.
import re
email = "[email protected]"
pattern = r"^[\w.-]+@[\w.-]+\.\w+$"
if re.match(pattern, email):
print("Valid email format")
85. Python Environment Variables
Sensitive or environment-specific values such as credentials and URLs should not normally be hard-coded into automation scripts.
import os
username = os.getenv("TEST_USERNAME")
password = os.getenv("TEST_PASSWORD")
print(username)
Environment variables can help keep configuration separate from source code.
86. Common Python Errors in Selenium Automation
| Error | Possible Cause |
| SyntaxError | Invalid Python syntax |
| IndentationError | Incorrect indentation |
| NameError | Variable or function name is unavailable |
| TypeError | Operation performed on an incompatible data type |
| IndexError | Invalid list index |
| KeyError | Dictionary key does not exist |
| AttributeError | Object does not provide the requested attribute |
| ImportError | Module or import cannot be resolved |
87. Common Selenium Coding Mistakes
- Using incorrect Python indentation.
- Using incorrect Selenium imports.
- Forgetting to call driver.quit().
- Using hard-coded sleeps everywhere.
- Using unstable locators.
- Writing duplicated automation logic.
- Hard-coding credentials in source code.
- Ignoring exceptions without understanding their cause.
- Creating very large functions instead of reusable methods.
- Mixing test data and automation logic unnecessarily.
88. Best Practices for Python Selenium Scripts
- Use meaningful variable and function names.
- Keep functions focused on one responsibility.
- Create reusable utility methods.
- Use Page Object Model for larger projects.
- Use explicit waits for dynamic UI synchronization.
- Avoid unnecessary time.sleep() calls.
- Keep test data separate from test logic.
- Use exception handling carefully.
- Use logging for debugging and execution tracking.
- Always close browser sessions properly.
- Keep locators maintainable.
- Use virtual environments for project dependencies.
- Use version control such as Git for automation projects.
89. Python Basics Learning Flow for Selenium
Python Syntax
↓
Variables & Data Types
↓
Operators
↓
Conditions
↓
Loops
↓
Functions
↓
Collections
↓
Exception Handling
↓
Modules & Packages
↓
OOP Concepts
↓
File Handling
↓
Selenium WebDriver
↓
Automation Scripts
↓
Page Object Model
↓
Automation Framework
90. Practical Project: Automate a Login Page
Objective
Create a Python Selenium script that opens a login page, enters credentials, clicks the login button, and validates the resulting page.
Suggested Flow
Open Browser
↓
Open Login URL
↓
Locate Username
↓
Enter Username
↓
Locate Password
↓
Enter Password
↓
Click Login
↓
Validate Result
↓
Close Browser
Practice Structure
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get("https://example.com/login")
driver.find_element(By.ID, "username").send_keys("admin")
driver.find_element(By.ID, "password").send_keys("admin123")
driver.find_element(By.ID, "login").click()
print("Login test executed")
finally:
driver.quit()
91. Practical Project: Product Search Automation
Build a small automation script that opens an e-commerce website, enters a product name into the search field, submits the search, and prints the page title or matching product names.
Python Concepts Used
- Variables
- Strings
- Functions
- Lists
- Loops
- Conditional statements
- Selenium WebDriver
- WebElement operations
92. Practical Project: Multiple User Login Data
Create multiple test data records using a Python list of dictionaries and execute the same login workflow for each record.
users = [
{"username": "admin", "password": "admin123"},
{"username": "tester", "password": "tester123"}
]
for user in users:
print("Testing:", user["username"])
93. Python Concepts Required Before Advanced Selenium
| Python Concept | Why It Matters in Selenium |
| Variables | Store browser objects, test data and values |
| Strings | Handle URLs, locators and text |
| Conditions | Implement validation and decision logic |
| Loops | Process multiple elements or test data |
| Functions | Create reusable automation operations |
| Lists | Store multiple values and WebElements |
| Dictionaries | Represent structured test data |
| Exceptions | Handle runtime failures appropriately |
| OOP | Build Page Objects and framework components |
| Modules | Organize reusable automation code |
| File Handling | Read and write test data and configuration |
94. Python vs Selenium Responsibilities
| Python | Selenium |
| Variables | Browser automation |
| Conditions | Element interaction |
| Loops | Finding web elements |
| Functions | Clicking and typing |
| Classes | Page automation |
| Collections | Working with multiple elements |
| Exception handling | Browser and WebDriver operations |
95. Recommended Python Selenium Project Structure
selenium_project/
│
├── tests/
│ ├── test_login.py
│ ├── test_search.py
│ └── test_checkout.py
│
├── pages/
│ ├── login_page.py
│ ├── home_page.py
│ └── checkout_page.py
│
├── utils/
│ ├── browser_utils.py
│ ├── test_data.py
│ └── logger.py
│
├── data/
│ └── users.csv
│
├── requirements.txt
└── README.md
96. requirements.txt
A requirements file can be used to record Python project dependencies.
selenium
Install dependencies with:
pip install -r requirements.txt
97. Interview Questions
Q1. Why is Python used with Selenium?
Python provides the programming logic required to create Selenium automation scripts and has a readable syntax, extensive libraries, and support for automation testing frameworks.
Q2. What Python concepts are important for Selenium?
Variables, data types, conditions, loops, functions, collections, exception handling, modules, file handling, and OOP are important foundations.
Q3. What is a list?
A list is an ordered and mutable collection used to store multiple values.
Q4. What is a dictionary?
A dictionary stores information as key-value pairs and is useful for structured test data.
Q5. What is a function?
A function is a reusable block of code that performs a specific task.
Q6. Why are functions useful in Selenium?
Functions reduce code duplication and allow common automation operations to be reused.
Q7. What is exception handling?
Exception handling allows a Python program to respond to runtime errors using mechanisms such as try and except.
Q8. Why is OOP important in Selenium?
OOP helps organize larger automation projects through classes, objects, inheritance, encapsulation, and reusable page components.
Q9. What is __init__()?
__init__() is commonly used as an initializer method for setting up object state when an object is created.
Q10. What is the difference between find_element() and find_elements()?
find_element() returns one matching WebElement, while find_elements() returns a collection of matching elements.
Q11. What is a tuple in Selenium?
A tuple is commonly used to represent locator information, such as (By.ID, "username").
Q12. Why should automation code be modular?
Modular code is easier to understand, reuse, debug, test, and maintain.
98. Quick Revision
| Topic | Key Point |
| Python | Programming language used to implement Selenium automation logic |
| Variable | Stores a value |
| String | Stores text |
| List | Stores ordered mutable values |
| Tuple | Stores ordered immutable values |
| Dictionary | Stores key-value data |
| Set | Stores unique values |
| Condition | Controls decision-making |
| Loop | Repeats operations |
| Function | Creates reusable logic |
| Class | Blueprint for objects |
| Object | Instance of a class |
| Exception | Runtime problem that can be handled |
| Module | Reusable Python code file |
| Selenium | Browser automation library/framework used with Python |
99. Best Learning Sequence
- Learn Python syntax.
- Understand variables and data types.
- Practice operators.
- Learn if, elif and else.
- Practice for and while loops.
- Learn lists, tuples, dictionaries and sets.
- Learn functions and parameters.
- Understand modules and imports.
- Practice exception handling.
- Learn file handling.
- Understand OOP concepts.
- Install Selenium.
- Learn WebDriver basics.
- Learn locators and WebElements.
- Learn waits and synchronization.
- Build reusable Page Objects.
- Move toward complete automation frameworks.
100. Final Summary
Python Basics for Selenium provides the programming foundation required to build reliable browser automation scripts. A Selenium tester should understand Python variables, strings, numbers, Boolean values, conditions, loops, functions, collections, exceptions, modules, file handling, and Object-Oriented Programming before moving into advanced automation framework development.
The combination of Python programming and Selenium WebDriver allows testers to create reusable automation scripts for login testing, form validation, search testing, e-commerce workflows, regression testing, cross-browser testing, and other web application scenarios.
Once the Python fundamentals are clear, learners can progress to Selenium WebDriver, locators, WebElements, waits, alerts, frames, windows, dropdowns, actions, Page Object Model, data-driven testing, TestNG/pytest-style test organization, reporting, CI/CD, and complete automation frameworks.
Course Resources
JustAcademy Selenium Training: https://www.justacademy.co/course-detail/selenium-training
Register for Course Demo: https://www.justacademy.co/register-for-course-demo