Selenium with Python – Module 1 (Interview Notes)
🔹 1. What is Selenium?
Definition:
Selenium is an open-source tool used for automating web applications across different
browsers and platforms.
Key Points:
o Works with multiple languages: Java, Python, C#, Ruby, JavaScript, PHP.
o Supports multiple browsers: Chrome, Firefox, Edge, Safari.
o Automates only web applications (not desktop/mobile apps directly).
o Very popular in QA automation.
👉 Interview Answer:
“Selenium is an open-source automation tool used for testing web applications across browsers and
platforms. It supports multiple languages, but Python is preferred because of its simplicity and rich
libraries.”
🔹 2. Selenium Suite (Components)
1. Selenium IDE
o A record-and-playback tool (mainly for quick prototyping, not used in real projects).
o Works as a browser extension (Chrome/Firefox).
2. Selenium WebDriver
o The most widely used component.
o Allows programmatic control of the browser using code.
o Supports all major languages & browsers.
3. Selenium Grid
o Used for parallel execution and cross-browser testing.
o Runs tests on multiple machines and environments simultaneously.
👉 Interview Tip:
If asked, always say WebDriver is the core part used in real-time projects.
🔹 3. Why use Selenium with Python?
Easy syntax → Less coding compared to Java/C#.
Rich libraries → Can integrate with unittest, pytest, pandas, requests.
Large community support → Quick solutions for errors.
Cross-platform → Works on Windows, Linux, macOS.
Integration → CI/CD tools (Jenkins, GitHub Actions).
👉 Interview Answer:
“Python with Selenium is popular because of its simple syntax, better readability, and rich ecosystem for
automation frameworks.”
🔹 4. Environment Setup
1. Install Python (3.10 or above)
o Download from [Link].
o Verify:
o python --version
o pip --version
2. Install Selenium
3. pip install selenium
4. Install WebDrivers
o ChromeDriver → For Google Chrome.
o GeckoDriver → For Firefox.
o EdgeDriver → For Microsoft Edge.
o Place driver in PATH or specify location in code.
5. IDE Setup
o Recommended: PyCharm / VS Code.
o Install Python plugin, configure interpreter, create a project.
👉 Interview Tip:
HR/Tech leads often ask:
“How do you install Selenium in Python?”
Answer: “Using pip install selenium and then setting up WebDriver like ChromeDriver.”
🔹 5. First Script (Python + Selenium)
from selenium import webdriver
# Launch browser
driver = [Link]()
# Open Google
[Link]("[Link]
# Print title
print("Page Title:", [Link])
# Close browser
[Link]()
Steps Explained:
1. Import webdriver from Selenium.
2. Create a Chrome browser instance.
3. Open Google.
4. Fetch and print the page title.
5. Close the browser session.
👉 Interview Questions on First Script:
Q: What does [Link]() do?
A: Opens the specified URL in the browser.
Q: Difference between [Link]() and [Link]()?
o close() → Closes current browser tab.
o quit() → Closes the entire browser session.
✅ Quick Revision (One-Liners for Interview)
Selenium is an open-source automation tool for web applications.
Selenium suite = IDE (record-playback), WebDriver (real coding), Grid (parallel execution).
Python is preferred because of simplicity + rich libraries + integration.
Install using: pip install selenium.
WebDriver required: ChromeDriver, GeckoDriver, EdgeDriver.
First script: Launch browser → Open URL → Fetch title → Quit browser.
close() vs quit() → Tab vs Entire session.
👉 Do you want me to also prepare Module 2: Python Refresher (with Q&A style interview notes +
examples) in the same way?
You said:
yes
ChatGPT said:
Super 👍 Let’s continue with Module 2: Python Refresher (Interview-Oriented Notes + Examples).
I’ll keep it in Q&A + code snippet style so you can quickly revise before interviews.
📘 Selenium with Python – Module 2 (Python Refresher for Test Automation)
🔹 1. Python Data Types
Commonly Asked Qs:
Q: What are Python’s basic data types used in automation?
A: int, float, str, bool, list, tuple, dict, set.
x = 10 # int
y = 10.5 # float
name = "Selenium" # string
is_ready = True # boolean
lst = [1, 2, 3] # list (mutable)
tup = (1, 2, 3) # tuple (immutable)
d = {"key": "val"}# dictionary
👉 Interview Tip: Lists are used heavily in test data handling, dictionaries for key-value structured data.
🔹 2. Conditional Statements
Q: How do you use conditions in Python?
age = 20
if age >= 18:
print("Eligible for driving test")
else:
print("Not eligible")
👉 Used for validations in test scripts (e.g., check if element exists).
🔹 3. Loops
Q: Difference between for and while loops?
for → used when you know the range/sequence.
while → runs until condition becomes False.
# For loop
for i in range(3):
print("Iteration", i)
# While loop
count = 0
while count < 3:
print("Count:", count)
count += 1
👉 Use Case: Iterate over list of elements (e.g., menu items, table rows).
🔹 4. Functions
Q: Why use functions in test automation?
A: To make code reusable and modular.
def add(a, b):
return a + b
print(add(5, 3)) # 8
👉 In automation, we wrap actions (like login, logout) inside functions.
🔹 5. Exception Handling
Q: How do you handle exceptions in Python?
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero not allowed")
finally:
print("Execution complete")
👉 Automation Use Case: Handle element not found errors.
🔹 6. File Handling
Q: How to read/write data from files in Python?
# Write
with open("[Link]", "w") as f:
[Link]("Selenium with Python\n")
# Read
with open("[Link]", "r") as f:
print([Link]())
👉 Used in automation for test data and reporting.
🔹 7. OOP Basics for Automation
Class & Object
class Car:
def __init__(self, brand):
[Link] = brand
def drive(self):
print([Link], "is driving")
c1 = Car("Tesla")
[Link]()
👉 In Selenium frameworks, we use classes for Page Object Model (POM).
Inheritance Example
class Parent:
def greet(self):
print("Hello from Parent")
class Child(Parent):
pass
obj = Child()
[Link]() # Inherits Parent method
👉 Used in frameworks to inherit base test classes.
🔹 8. Practical Automation-Oriented Example
Q: Show a small script mixing Python concepts with Selenium.
from selenium import webdriver
urls = ["[Link] "[Link]
driver = [Link]()
for site in urls:
try:
[Link](site)
print("Opened:", [Link])
except Exception as e:
print("Error:", e)
[Link]()
👉 Demonstrates: lists, loops, try/except, functions.
✅ Quick Revision (Interview Cheatsheet)
Lists = mutable, Tuples = immutable.
Dict = key-value storage, widely used for config/test data.
if-else used for validations in tests.
for loop → fixed range, while loop → conditional.
Functions → reusability, OOP → structure (important for POM).
Exception Handling prevents test case failure due to runtime errors.
File handling → store/read test data.
👉 Do you want me to move to Module 3: Selenium WebDriver Basics (with Q&A + scripts for
interview prep) next?
You said:
yes
ChatGPT said:
Great 👍 Let’s move to Module 3: Selenium WebDriver Basics (Interview Notes + Scripts).
I’ll keep it in Q&A + example code + interview tips style for quick revision.
📘 Selenium with Python – Module 3 (WebDriver Basics)
🔹 1. What is Selenium WebDriver?
Definition:
WebDriver is a browser automation framework that allows us to control browsers
programmatically.
Supports Chrome, Firefox, Edge, Safari.
Uses JSON Wire Protocol / W3C WebDriver protocol to communicate with browsers.
👉 Interview Answer:
“Selenium WebDriver is the core component of Selenium that directly interacts with browsers to perform
automation tasks like clicking, typing, and navigating.”
🔹 2. Browser Navigation Commands
Q: What are common navigation commands in Selenium?
from selenium import webdriver
driver = [Link]()
[Link]("[Link] # Open URL
[Link]("[Link] # Open another URL
[Link]() # Go back
[Link]() # Go forward
[Link]() # Refresh page
print("Page Title:", [Link]) # Get page title
print("Current URL:", driver.current_url)
[Link]()
👉 Interview Tip: They may ask difference between:
[Link]() → closes current tab
[Link]() → closes the whole browser session
🔹 3. Window Handling
Q: How do you handle multiple tabs/windows in Selenium?
driver.execute_script("[Link]('[Link]
driver.execute_script("[Link]('[Link]
windows = driver.window_handles
driver.switch_to.window(windows[1]) # Switch to 2nd tab
print([Link])
[Link]() # Close current tab
driver.switch_to.window(windows[0]) # Switch back
👉 Use Case: E-commerce checkout → multiple tabs (cart, payment, confirmation).
🔹 4. Get Page Info
Q: How do you get page details?
print([Link]) # Page title
print(driver.current_url) # Current URL
print(driver.page_source) # HTML source
👉 Used in validations (e.g., verify correct page opened).
🔹 5. Taking Screenshots
Q: How do you capture a screenshot in Selenium?
[Link]("[Link]
driver.save_screenshot("[Link]")
👉 Useful for test reporting and debugging failures.
🔹 6. Practical Example – First Automation Script
Q: Can you write a simple Selenium script to open Google and print its title?
from selenium import webdriver
driver = [Link]()
[Link]("[Link]
print("Title:", [Link])
[Link]()
👉 This is often the first demo question in interviews.
✅ Quick Revision (Interview Cheatsheet)
WebDriver = core Selenium component for browser automation.
Common commands:
o get(url) → Open webpage
o back(), forward(), refresh() → Navigation
o title, current_url, page_source → Page info
close() vs quit() = tab vs full session.
window_handles used for multi-tab handling.
save_screenshot() used in reporting/debugging.
👉 Do you want me to continue with Module 4: Locators & Web Elements (most asked in interviews,
with XPath & CSS examples)?
You said:
yes
ChatGPT said:
Perfect 🚀 Let’s dive into Module 4: Locators & Web Elements – this is one of the most frequently
asked topics in Selenium interviews.
I’ll prepare it in Q&A style + code + interview tips for quick recall.
📘 Selenium with Python – Module 4 (Locators & Web Elements)
🔹 1. What are Locators in Selenium?
Definition: Locators are ways to identify elements on a web page (textbox, button, link, etc.) so
Selenium can interact with them.
Commonly used locators:
o ID
o Name
o ClassName
o TagName
o LinkText / PartialLinkText
o CSS Selector
o XPath
👉 Interview Answer:
“Locators in Selenium are used to find and interact with web elements. XPath and CSS are the most
powerful and commonly used locators.”
🔹 2. Locator Examples
Q: Show how to use different locators.
from selenium import webdriver
from [Link] import By
driver = [Link]()
[Link]("[Link]
# By ID
search_box = driver.find_element([Link], "APjFqb")
# By Name
search_box = driver.find_element([Link], "q")
# By ClassName
btn = driver.find_element(By.CLASS_NAME, "gNO89b")
# By CSS Selector
btn = driver.find_element(By.CSS_SELECTOR, "input[name='btnK']")
# By XPath
btn = driver.find_element([Link], "//input[@name='btnK']")
[Link]()
👉 Interview Tip: Prefer ID or Name when available (fastest, stable). Use XPath/CSS for complex
cases.
🔹 3. XPath in Detail
Types of XPath:
1. Absolute XPath → Starts from root (/html/body/...) → Not recommended.
2. Relative XPath → Starts from // → More stable.
Examples:
//input[@name='q'] # Attribute based
//button[text()='Login'] # Text based
//div[contains(@class,'menu')] # Partial match
//input[@type='text' and @id='username'] # Multiple conditions
👉 Interview Q: Difference between Absolute and Relative XPath?
Absolute → complete path, fragile.
Relative → starts from anywhere, preferred.
🔹 4. CSS Selector in Detail
Examples:
input[name='q'] /* Attribute based */
[Link]-btn /* Class selector */
#username /* ID selector */
[Link] > ul > li /* Child selector */
div[class*='header'] /* Contains */
👉 Interview Tip: CSS is faster than XPath in Chrome but less powerful for navigating backwards.
🔹 5. WebElement Methods
Q: How do you interact with elements once located?
element = driver.find_element([Link], "q")
element.send_keys("Selenium with Python") # Type text
[Link]() # Clear text
[Link]() # Click button
print(element.is_displayed()) # True/False
print(element.is_enabled()) # True/False
print(element.is_selected()) # For checkboxes/radio buttons
👉 Commonly used in form filling, button clicks, and validations.
🔹 6. Handling Multiple Elements
Q: How do you get a list of elements?
links = driver.find_elements(By.TAG_NAME, "a")
print("Total links:", len(links))
for link in links:
print([Link])
👉 Use case: Extract all links, menu items, or table rows.
🔹 7. Practical Example – Google Search Automation
from selenium import webdriver
from [Link] import By
import time
driver = [Link]()
[Link]("[Link]
# Locate search box by Name
search = driver.find_element([Link], "q")
search.send_keys("Selenium with Python")
[Link](1)
# Locate search button by XPath and click
btn = driver.find_element([Link], "//input[@name='btnK']")
[Link]()
print("Title after search:", [Link])
[Link]()
👉 Demonstrates: Locators + send_keys() + click().
✅ Quick Revision (Interview Cheatsheet)
Selenium locators = ways to find elements on web page.
Common locators: ID, Name, ClassName, CSS, XPath, LinkText.
XPath → best for complex structures, supports text & conditions.
CSS → faster, concise but can’t move backward in DOM.
find_element() → returns first match.
find_elements() → returns list of elements.
WebElement methods: click(), send_keys(), clear(), is_displayed(), is_enabled(), is_selected().
👉 Next, shall I prepare Module 5: Advanced User Interactions (Mouse/Keyboard Actions, Alerts,
iFrames, File Upload/Download) – with interview Q&A?
You said:
yes
ChatGPT said:
Perfect 🚀 Let’s go ahead with Module 5: Advanced User Interactions – this is another favorite area in
interviews because it covers real-life test automation challenges.
I’ll keep it Q&A style + examples + interview tips.
📘 Selenium with Python – Module 5 (Advanced User Interactions)
🔹 1. ActionChains (Mouse & Keyboard)
Q: What is ActionChains in Selenium?
A class in Selenium to handle complex user gestures: hover, drag & drop, double-click, right-
click, key press.
from selenium import webdriver
from [Link].action_chains import ActionChains
from [Link] import By
driver = [Link]()
[Link]("[Link]
source = driver.find_element([Link], "drag1")
target = driver.find_element([Link], "div2")
actions = ActionChains(driver)
actions.drag_and_drop(source, target).perform()
👉 Interview Tip: Mention that ActionChains simulates real mouse/keyboard actions.
🔹 2. Mouse Actions
Examples:
element = driver.find_element([Link], "menu")
# Hover
ActionChains(driver).move_to_element(element).perform()
# Right-click
ActionChains(driver).context_click(element).perform()
# Double-click
ActionChains(driver).double_click(element).perform()
👉 Use Case: Hover menus, context menus, double-click fields.
🔹 3. Keyboard Actions
from [Link] import Keys
search = driver.find_element([Link], "q")
search.send_keys("Selenium with Python")
search.send_keys([Link]) # Press Enter key
👉 Useful when login or search requires keyboard shortcuts.
🔹 4. Handling Alerts & Popups
Q: How do you handle JavaScript alerts?
alert = driver.switch_to.alert
print([Link]) # Read alert message
[Link]() # Click OK
# [Link]() # Click Cancel
👉 Interview Tip: They often ask difference:
accept() → OK
dismiss() → Cancel
🔹 5. Handling iFrames
Q: How do you switch to an iFrame in Selenium?
# Switch by index
driver.switch_to.frame(0)
# Switch by name or ID
driver.switch_to.frame("iframeResult")
# Switch using WebElement
iframe = driver.find_element([Link], "//iframe[@id='frame1']")
driver.switch_to.frame(iframe)
# Switch back to main content
driver.switch_to.default_content()
👉 Use Case: Login forms, ads, embedded videos often come inside iFrames.
🔹 6. Multiple Browser Windows/Tabs
driver.execute_script("[Link]('[Link]
handles = driver.window_handles
driver.switch_to.window(handles[1]) # Switch to new tab
[Link]()
driver.switch_to.window(handles[0]) # Switch back
👉 Interview Q: How do you switch between windows?
A: Using driver.window_handles and switch_to.window(handle).
🔹 7. File Upload
upload = driver.find_element([Link], "fileInput")
upload.send_keys("C:\\Users\\Jitendra\\[Link]")
👉 Interview Tip: File upload can be done using send_keys(path) if it’s an <input type="file">.
🔹 8. File Download
Controlled via browser settings (preferences) before launching browser.
Example (Chrome):
from [Link] import Options
options = Options()
prefs = {"download.default_directory": "C:\\Downloads"}
options.add_experimental_option("prefs", prefs)
driver = [Link](options=options)
[Link]("[Link]
👉 Used for validating file download workflows.
🔹 9. Example – Full Interaction Flow
from selenium import webdriver
from [Link] import By
from [Link].action_chains import ActionChains
from [Link] import Keys
import time
driver = [Link]()
[Link]("[Link]
# Search with keyboard
search = driver.find_element([Link], "q")
search.send_keys("Python Selenium")
search.send_keys([Link])
[Link](2)
# Screenshot after search
driver.save_screenshot("[Link]")
[Link]()
✅ Quick Revision (Interview Cheatsheet)
ActionChains → For mouse & keyboard actions.
Mouse actions: click(), double_click(), context_click(), move_to_element().
Keyboard actions: send_keys([Link]), [Link], [Link].
Alerts: accept(), dismiss(), text.
iFrames: switch_to.frame() and switch_to.default_content().
Windows/Tabs: window_handles + switch_to.window().
File Upload: send_keys(file_path).
File Download: set browser preferences before launching driver.
👉 Do you want me to move on to Module 6: Synchronization (Waits, Stale Element, Interview Qs)
next?
You said:
yes
ChatGPT said:
Super 👍 Let’s continue with Module 6: Synchronization in Selenium (Waits & Timing Issues) –
👉 One of the most common interview topics, because synchronization is the key to stable test
automation.
📘 Selenium with Python – Module 6 (Synchronization & Waits)
🔹 1. Why Synchronization?
Web applications are dynamic – elements may load late, AJAX calls may delay, or pages may take time
to render.
Without waits, you’ll get errors like:
NoSuchElementException
ElementNotVisibleException
StaleElementReferenceException
👉 Interview Tip: If asked “Why synchronization is needed?” → Answer: To handle timing issues
between Selenium script speed and web application response speed.
🔹 2. Types of Waits in Selenium
✅ (a) Implicit Wait
Applies globally for all elements.
Tells Selenium to keep trying until timeout.
from selenium import webdriver
from [Link] import By
driver = [Link]()
driver.implicitly_wait(10) # wait up to 10 seconds
[Link]("[Link]
search = driver.find_element([Link], "q")
search.send_keys("Selenium Python")
👉 Interview Q:
Q: What is the drawback of implicit wait?
A: Works for all elements, but not suitable for specific conditions (like clickable, visible, etc.).
✅ (b) Explicit Wait
Wait for a specific condition (recommended).
from [Link] import WebDriverWait
from [Link] import expected_conditions as EC
[Link]("[Link]
search = WebDriverWait(driver, 10).until(
EC.presence_of_element_located(([Link], "q"))
)
search.send_keys("Selenium Explicit Wait")
👉 Common Expected Conditions:
presence_of_element_located
visibility_of_element_located
element_to_be_clickable
alert_is_present
frame_to_be_available_and_switch_to_it
✅ (c) Fluent Wait
Like Explicit Wait, but with polling frequency and ignored exceptions.
from [Link] import WebDriverWait
from [Link] import TimeoutException
wait = WebDriverWait(driver, 15, poll_frequency=2, ignored_exceptions=[TimeoutException])
element = [Link](EC.visibility_of_element_located(([Link], "q")))
element.send_keys("Python Fluent Wait")
👉 Interview Tip: Fluent wait is mostly asked as a theory question. In Python, it’s handled with
WebDriverWait + polling.
🔹 3. StaleElementReferenceException
Q: What is StaleElementReferenceException?
Occurs when DOM changes after finding element.
Example: Page reloads, element refreshed, or AJAX updates the DOM.
Solution:
Re-locate the element again.
Use Explicit/Fluent Waits.
try:
element = driver.find_element([Link], "username")
element.send_keys("admin")
except StaleElementReferenceException:
element = driver.find_element([Link], "username")
element.send_keys("admin")
🔹 4. Sleep (Not Recommended)
[Link](5) → Hardcoded wait.
Slows down test execution.
Only use for debugging.
🔹 5. Example – Login with Explicit Waits
from selenium import webdriver
from [Link] import By
from [Link] import WebDriverWait
from [Link] import expected_conditions as EC
driver = [Link]()
[Link]("[Link]
wait = WebDriverWait(driver, 10)
username = [Link](EC.presence_of_element_located(([Link], "username")))
username.send_keys("Admin")
password = driver.find_element([Link], "password")
password.send_keys("admin123")
login_btn = [Link](EC.element_to_be_clickable(([Link], "//button[@type='submit']")))
login_btn.click()
✅ Quick Interview Cheatsheet (Module 6)
Implicit Wait → Applies globally, not specific.
Explicit Wait → Best choice; wait for specific conditions.
Fluent Wait → Explicit Wait + polling frequency.
Sleep → Avoid (hardcoded).
StaleElementReferenceException → Happens when DOM refreshes. Fix: re-locate element +
use waits.
Best Practice → Use Explicit Wait with Expected Conditions.
👉 Next, do you want me to move to Module 7: Page Object Model (POM) & Framework Design (big
interview topic, often asked for automation framework design)?
You said:
yes
ChatGPT said:
Great choice 🚀 – this is a high-value interview topic!
Let’s move into Module 7: Page Object Model (POM) & Framework Design.
📘 Selenium with Python – Module 7 (POM & Framework Design)
🔹 1. What is Page Object Model (POM)?
Design Pattern used in test automation.
Each web page is represented as a class in Python.
All page elements (locators) + methods (actions) are stored inside that class.
Tests use these page classes → makes scripts reusable, maintainable, scalable.
👉 Interview Tip: If asked “Why POM?” → Answer: To avoid duplicate code, improve maintainability,
and support large automation projects.
🔹 2. Traditional vs POM
❌ Without POM
driver.find_element([Link], "username").send_keys("Admin")
driver.find_element([Link], "password").send_keys("admin123")
driver.find_element([Link], "loginBtn").click()
✅ With POM
login_page = LoginPage(driver)
login_page.enter_username("Admin")
login_page.enter_password("admin123")
login_page.click_login()
👉 Cleaner, reusable, easy to maintain.
🔹 3. POM Class Structure Example
login_page.py
from [Link] import By
class LoginPage:
def __init__(self, driver):
[Link] = driver
self.username_input = ([Link], "username")
self.password_input = ([Link], "password")
self.login_button = ([Link], "loginBtn")
def enter_username(self, username):
[Link].find_element(*self.username_input).send_keys(username)
def enter_password(self, password):
[Link].find_element(*self.password_input).send_keys(password)
def click_login(self):
[Link].find_element(*self.login_button).click()
🔹 4. Test Case Using POM
test_login.py
import unittest
from selenium import webdriver
from login_page import LoginPage
class LoginTest([Link]):
def setUp(self):
[Link] = [Link]()
[Link]("[Link]
def test_valid_login(self):
login_page = LoginPage([Link])
login_page.enter_username("Admin")
login_page.enter_password("admin123")
login_page.click_login()
[Link]("Dashboard", [Link])
def tearDown(self):
[Link]()
if __name__ == "__main__":
[Link]()
👉 Interview Tip: They often ask – “How do you implement POM in Python?” → Show this example.
🔹 5. Advanced POM with BasePage
To avoid repeating driver methods, create a BasePage.
base_page.py
class BasePage:
def __init__(self, driver):
[Link] = driver
def click(self, locator):
[Link].find_element(*locator).click()
def type(self, locator, text):
[Link].find_element(*locator).send_keys(text)
def get_text(self, locator):
return [Link].find_element(*locator).text
👉 Now, all page classes can inherit from BasePage.
🔹 6. POM + Test Framework (Hybrid)
A typical framework includes:
Test Cases → Business logic
Page Objects → Page locators & actions
Utilities → Logging, Reporting, Config, Excel/CSV readers
Test Runner → unittest, pytest, or behave (BDD)
Reports → HTMLTestRunner / Allure
👉 Interview Q: “What framework did you build in Selenium with Python?”
Expected Answer: A Hybrid Framework (combination of POM + Data Driven + Utilities).
🔹 7. Example Folder Structure
automation_framework/
│── tests/
│ └── test_login.py
│── pages/
│ └── login_page.py
│ └── dashboard_page.py
│── utils/
│ └── base_page.py
│ └── config_reader.py
│── reports/
│── drivers/
│── [Link] (for pytest)
🔹 8. Reporting (Interview Highlight)
In Python Selenium:
o Pytest + Allure Reports
o unittest + HTMLTestRunner
Example:
pip install pytest allure-pytest
pytest --alluredir=reports/
allure serve reports/
✅ Quick Interview Cheatsheet (Module 7)
POM = Page = Class, Element = Variable, Action = Method.
Benefits → Reusability, Maintainability, Scalability.
BasePage → Reusable methods for all pages.
Framework Types:
o Data Driven (external data – Excel/CSV/DB)
o Keyword Driven (keywords = actions)
o Hybrid Framework (mix of both + POM)
o BDD (Cucumber/Behave + POM)
👉 Next up, do you want me to go into Module 8: Data-Driven Testing (Excel, CSV, JSON, DB
integration)? (This is another favorite interview area).
You said:
yes
ChatGPT said:
Perfect 🚀 Let’s move into Module 8: Data-Driven Testing (DDT) –
👉 This is an interview hot topic, because real-world test automation must handle multiple sets of test
data.
📘 Selenium with Python – Module 8 (Data-Driven Testing)
🔹 1. What is Data-Driven Testing (DDT)?
A testing approach where test data is separated from test scripts.
Same test script runs multiple times with different inputs & expected outputs.
Helps cover more scenarios with less code.
👉 Interview Tip: If asked “Why DDT?” → Answer: Reduces duplication, improves reusability, and
makes test automation scalable.
🔹 2. Ways to Handle Test Data in Python Selenium
1. Excel Files (openpyxl, xlrd, pandas)
2. CSV Files (Python’s csv module, pandas)
3. JSON Files (json module)
4. Databases (MySQL, PostgreSQL, SQLite)
5. Config Files (.ini, .yaml, .env)
🔹 3. Example: Read Data from Excel
📂 Using openpyxl
import openpyxl
# Load Excel
workbook = openpyxl.load_workbook("[Link]")
sheet = workbook["Sheet1"]
rows = sheet.max_row
cols = sheet.max_column
for r in range(2, rows+1): # skip header
username = [Link](r, 1).value
password = [Link](r, 2).value
print(username, password)
👉 Common interview Q: “How do you read test data from Excel in Python?” → Show this.
🔹 4. Example: DDT with Excel + Selenium
from selenium import webdriver
from [Link] import By
import openpyxl
import time
driver = [Link]()
[Link]("[Link]
workbook = openpyxl.load_workbook("[Link]")
sheet = [Link]
for r in range(2, sheet.max_row + 1):
username = [Link](r, 1).value
password = [Link](r, 2).value
driver.find_element([Link], "username").send_keys(username)
driver.find_element([Link], "password").send_keys(password)
driver.find_element([Link], "//button[@type='submit']").click()
[Link](2)
[Link]("[Link] # reset for next login
🔹 5. Example: Read Data from CSV
import csv
with open("[Link]", "r") as file:
reader = [Link](file)
next(reader) # skip header
for row in reader:
print("Username:", row[0], "Password:", row[1])
🔹 6. Example: Read Data from JSON
import json
with open("[Link]") as f:
data = [Link](f)
for user in data["users"]:
print(user["username"], user["password"])
👉 JSON is often used for API + Selenium hybrid frameworks.
🔹 7. Example: Database-Driven Testing
import sqlite3
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT username, password FROM users")
for row in [Link]():
print(row[0], row[1])
[Link]()
🔹 8. DDT with Pytest (Parametrize)
import pytest
@[Link]("username,password", [
("Admin", "admin123"),
("InvalidUser", "wrongpass"),
])
def test_login(username, password):
print(f"Testing login with {username} / {password}")
👉 Interview Tip: If they ask about “data-driven in Pytest” → show @[Link].
🔹 9. Typical DDT Framework Flow
1. Read test data from Excel/CSV/DB.
2. Pass data to Selenium test script.
3. Execute test multiple times with different inputs.
4. Log results (Pass/Fail) back into Excel/Report.
✅ Quick Interview Cheatsheet (Module 8)
DDT = separate data from test script.
Data sources: Excel, CSV, JSON, DB, Config.
Common library: openpyxl for Excel.
Pytest supports DDT via @[Link].
Advantage: Reusability + Scalability.
Frameworks often use Hybrid (POM + DDT + Utilities).
👉 Next, do you want me to cover Module 9: Logging, Reporting & Test Execution (Pytest + Allure,
HTML Reports, CI/CD)?
You said:
yes
ChatGPT said:
Perfect 🙌 – now we’re at Module 9: Logging, Reporting & Test Execution –
👉 This is the most important module for interviews, because companies want professional
automation frameworks that generate logs & reports and integrate with CI/CD.
📘 Selenium with Python – Module 9 (Logging, Reporting & Execution)
🔹 1. Why Logging & Reporting?
Logging → Tracks execution flow (debugging & analysis).
Reporting → Summarizes test results (Pass/Fail, Screenshots, Errors).
CI/CD Integration → Ensures reports are available after automated builds.
👉 Interview Tip: If asked “How do you generate reports in Selenium with Python?” → Answer: Using
unittest + HTMLTestRunner or pytest + Allure Reports.
🔹 2. Logging in Python
Using Python’s built-in logging module.
import logging
[Link](filename="[Link]",
level=[Link],
format="%(asctime)s - %(levelname)s - %(message)s")
[Link]("Test started")
[Link]("Element not found, retrying...")
[Link]("Login failed")
[Link]("Test finished")
👉 Log Levels: DEBUG < INFO < WARNING < ERROR < CRITICAL
🔹 3. HTML Reports with unittest + HTMLTestRunner
import unittest
from selenium import webdriver
import HtmlTestRunner
class GoogleTest([Link]):
def setUp(self):
[Link] = [Link]()
def test_google(self):
[Link]("[Link]
[Link]("Google", [Link])
def tearDown(self):
[Link]()
if __name__ == "__main__":
[Link](
testRunner=[Link](output="reports/")
)
👉 Generates a beautiful HTML report inside reports/.
🔹 4. Pytest + Allure Reports
Install Allure:
pip install pytest allure-pytest
Run tests with Allure report:
pytest --alluredir=reports/
allure serve reports/
👉 Produces a dashboard-style report (with graphs, timelines, screenshots).
👉 Interview Tip: If asked “Which report tool do you prefer?” → Say Allure (modern, CI/CD friendly).
🔹 5. Screenshot on Failure
import pytest
@[Link]
def driver():
from selenium import webdriver
driver = [Link]()
yield driver
[Link]()
def test_google_search(driver):
[Link]("[Link]
try:
assert "Bing" in [Link] # Wrong on purpose
except AssertionError:
driver.save_screenshot("[Link]")
raise
👉 Very common in frameworks → attach screenshots to reports.
🔹 6. Running Tests in Parallel
pip install pytest-xdist
pytest -n 4 # runs tests in 4 parallel threads
👉 Useful in interviews: “How to speed up test execution?” → Parallel runs with pytest-xdist.
🔹 7. CI/CD Integration (Jenkins/GitHub Actions)
Steps:
1. Install dependencies (pip install -r [Link])
2. Run pytest/unittest
3. Generate reports (HTML/Allure)
4. Publish reports in Jenkins/GitHub Actions
👉 Interview Tip: Say – “I have integrated Selenium Python framework with Jenkins for nightly builds,
where test results are published as HTML/Allure reports.”
🔹 8. Example Folder Structure (With Reports & Logs)
automation_framework/
│── tests/
│ └── test_login.py
│── pages/
│ └── login_page.py
│── utils/
│ └── base_page.py
│ └── [Link]
│── reports/
│── logs/
│── drivers/
│── [Link]
✅ Quick Interview Cheatsheet (Module 9)
Logging → Python logging module.
Reports:
o HTMLTestRunner → unittest
o Allure Reports → pytest (preferred in CI/CD).
Parallel Execution → pytest-xdist.
Screenshots on Failure → driver.save_screenshot().
CI/CD → Jenkins or GitHub Actions for automation pipeline.
👉 Next, shall we dive into Module 10: Selenium Grid & Parallel Execution (Cross-Browser, Remote
WebDriver, Docker)?
(This is another favorite interview area when they ask about scalability.)
You said:
yes
ChatGPT said:
Awesome 🚀 – now let’s move to Module 10: Selenium Grid & Parallel Execution –
👉 This is a favorite interview area when companies ask about scalability, cross-browser testing, and
CI/CD integration.
📘 Selenium with Python – Module 10 (Selenium Grid & Parallel Execution)
🔹 1. What is Selenium Grid?
A tool for distributed test execution.
Run tests on multiple machines, browsers, and OS in parallel.
Uses Hub & Node architecture.
👉 Interview Tip: If asked “Why use Grid?” → Answer: To run tests faster, on different browsers and
platforms simultaneously.
🔹 2. Selenium Grid Architecture
Hub: Central server that controls test execution.
Nodes: Machines where tests actually run (different OS/browsers).
You send tests → Hub distributes them → Nodes execute.
🔹 3. Start Selenium Grid (Standalone JAR)
1. Download Selenium Server (Jar) from official site.
2. Start Grid Hub + Nodes:
# Start Hub
java -jar [Link] hub
# Start Node (example: Chrome)
java -jar [Link] node --port 5555 --detect-drivers true
👉 New Selenium 4 supports Hub + Node in one standalone server.
🔹 4. Remote WebDriver Example (Python)
from selenium import webdriver
from [Link] import By
grid_url = "[Link]
options = [Link]()
driver = [Link](command_executor=grid_url, options=options)
[Link]("[Link]
print([Link])
[Link]()
👉 Instead of local [Link](), we connect to remote Grid Hub.
🔹 5. Parallel Execution with pytest-xdist
Install:
pip install pytest-xdist
Run tests in parallel:
pytest -n 4 # 4 parallel threads
👉 Interview Tip: They often ask – “How do you speed up Selenium execution?”
Answer: Use pytest-xdist for parallel threads or Selenium Grid for distributed execution.
🔹 6. Cross-Browser Testing
import pytest
from selenium import webdriver
@[Link]("browser", ["chrome", "firefox"])
def test_open_google(browser):
if browser == "chrome":
driver = [Link]()
elif browser == "firefox":
driver = [Link]()
[Link]("[Link]
assert "Google" in [Link]
[Link]()
👉 Covers multiple browsers in a single run.
🔹 7. Selenium Grid with Docker
Why Docker? → Easy setup of multiple browser nodes (Chrome, Firefox, Edge).
Example setup:
docker pull selenium/hub
docker pull selenium/node-chrome
docker pull selenium/node-firefox
# Start Hub
docker run -d -p 4444:4444 --name selenium-hub selenium/hub
# Start Chrome Node
docker run -d --link selenium-hub:hub selenium/node-chrome
# Start Firefox Node
docker run -d --link selenium-hub:hub selenium/node-firefox
👉 Interview gold: If you mention Docker + Selenium Grid, you’ll stand out.
🔹 8. CI/CD + Grid Integration
In Jenkins/GitHub Actions:
o Start Grid (Hub + Nodes).
o Run tests in parallel on different browsers.
o Generate reports (Allure/HTML).
Ensures tests run across multiple environments automatically.
✅ Quick Interview Cheatsheet (Module 10)
Grid = Hub + Nodes (distributed testing).
Use case = cross-browser, parallel, multi-OS execution.
RemoteWebDriver → Connects to Grid.
pytest-xdist → Parallel execution in local machine.
Docker + Grid → Easiest way to scale.
CI/CD → Integrate Grid with Jenkins for cross-browser automation pipeline.
👉 Next up: Do you want me to cover Module 11: API Testing with Selenium + Python (using requests
+ hybrid frameworks) or jump into Module 12: Advanced Interview Questions & Best Practices?
You said:
yes
ChatGPT said:
Got it ✅ Let’s move into Module 11: API Testing with Python (and Hybrid with Selenium) –
👉 Even though Selenium is mainly for UI testing, in real projects we often combine it with API testing to
validate backend + frontend together.
This is a hot interview area, especially when they ask:
“Can you integrate API and UI testing in one framework?”
📘 Selenium with Python – Module 11 (API Testing + Hybrid Framework)
🔹 1. Why API + Selenium Together?
UI tests alone are slow & flaky.
API tests are faster and validate backend logic.
In hybrid frameworks, we:
o Use API testing for data validation, DB checks, service calls.
o Use Selenium for UI workflows.
👉 Example: Verify login → first test login API → then validate UI reflects correct state.
🔹 2. Python Library for API Testing
requests → most widely used.
Supports GET, POST, PUT, DELETE.
Can validate status codes, headers, response body.
Install:
pip install requests
🔹 3. Example: Simple GET Request
import requests
response = [Link]("[Link]
print(response.status_code) # 200
print([Link]()) # JSON response
👉 Interview Q: “Which Python library do you use for API testing?” → Answer: requests.
🔹 4. Example: POST Request with JSON
import requests
payload = {"name": "Jitendra", "job": "QA Engineer"}
response = [Link]("[Link] json=payload)
print(response.status_code) # 201
print([Link]()) # {"id": "...", "createdAt": "..."}
👉 Used for login, form submission, etc.
🔹 5. API + Selenium Hybrid Example
Imagine a login flow:
1. First test the Login API → get token.
2. Then use Selenium to check UI loads correctly.
import requests
from selenium import webdriver
from [Link] import By
# Step 1: API Login
payload = {"username": "Admin", "password": "admin123"}
api_response = [Link]("[Link] json=payload)
token = api_response.json()["token"]
# Step 2: UI Validation
driver = [Link]()
[Link]("[Link]
driver.add_cookie({"name": "sessionToken", "value": token})
[Link]()
assert "Dashboard" in [Link]
[Link]()
👉 Best Practice: Use API for setup (like creating user/order) → then validate with UI.
🔹 6. API Validation with Assertions
response = [Link]("[Link]
data = [Link]()
assert response.status_code == 200
assert data["page"] == 2
assert len(data["data"]) > 0
👉 Interview Tip: They often ask “How do you validate API responses?” → Answer: By checking status
code, response body, headers.
🔹 7. API Testing in Pytest (with Fixtures)
import pytest
import requests
@[Link]
def base_url():
return "[Link]
def test_get_users(base_url):
response = [Link](f"{base_url}/users?page=2")
assert response.status_code == 200
assert "data" in [Link]()
👉 Works well in Hybrid Selenium + API framework.
🔹 8. Real-World Use Cases
Create a user via API → Login via UI → Validate user exists.
Submit order via UI → Validate order status via API.
Verify DB/API response matches UI display.
✅ Quick Interview Cheatsheet (Module 11)
requests library for API testing.
Methods: get(), post(), put(), delete().
Validate: status_code, json body, headers.
Hybrid approach: Use API for setup/validation, Selenium for UI checks.
Best practice: Don’t overuse Selenium when API validation is faster.
👉 Next, should I take you into Module 12: Advanced Selenium Interview Questions & Best Practices
(mock Q&A style) so you’ll be fully prepared for interviews?
You said:
yes
ChatGPT said:
Perfect ✅ Let’s wrap up with the final module – Advanced Interview Questions & Best Practices
(Module 12).
This will help you face real interview scenarios confidently.
📘 Selenium with Python – Module 12 (Advanced Interview Questions & Best Practices)
🔹 1. Selenium + Python Advanced Interview Questions
⚡ General Selenium
1. Q: What are Selenium limitations?
A: Can’t test Captcha, OTP, Barcodes, Desktop Apps, non-HTML elements. Needs third-party
tools.
2. Q: Difference between Selenium 3 and Selenium 4?
A:
o W3C WebDriver standard.
o Relative locators.
o Chrome DevTools Protocol (network, console logs).
o No need for standalone JAR for Grid.
3. Q: How to handle synchronization in Selenium?
A: Use Implicit wait, Explicit wait (WebDriverWait), FluentWait.
⚡ Python + Selenium
4. Q: How to manage test data in Selenium Python?
A: Use Excel (openpyxl), JSON, CSV, DB connection.
5. Q: How do you handle dynamic elements in Selenium?
A: Use XPath functions (contains, starts-with, normalize-space) or CSS selectors.
6. Q: How do you capture screenshots in Selenium Python?
7. driver.save_screenshot("[Link]")
👉 Mention usage in reporting.
⚡ Test Frameworks & Parallelism
7. Q: Which test frameworks are used with Selenium + Python?
A: unittest, pytest, robot framework, behave (BDD).
8. Q: How do you run tests in parallel?
A: pytest-xdist, Selenium Grid, Dockerized nodes.
9. Q: What’s your test execution strategy?
A:
o Smoke tests → every build.
o Regression suite → nightly/weekly.
o Cross-browser suite → parallel/Grid.
⚡ API + Selenium Integration
10. Q: Why combine API and UI testing?
A: Faster validation, reduces flaky UI tests, ensures backend + frontend sync.
⚡ CI/CD & Reporting
11. Q: How do you integrate Selenium tests in CI/CD?
A: Use Jenkins/GitHub Actions, trigger test suite post-deployment, store reports (Allure,
Extent, HTML).
12. Q: How do you generate reports in Selenium + Python?
A: Use pytest-html, allure-pytest, or custom logging.