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