Tuesday, June 16

Selenium Automation Coding Questions



 Selenium Automation Coding Questions


Open Browser and Launch Website

Question:
Write a Selenium script to open Chrome and launch a website.

Answer (Python + Selenium):

from selenium import webdriver

# Launch Chrome
driver = webdriver.Chrome()

# Open website
driver.get("https://www.google.com")

# Maximize window
driver.maximize_window()

# Close browser
driver.quit()

What interviewer checks:
✔ Selenium basics
✔ WebDriver knowledge


Locate Element and Perform Login

Question:
Write code to enter username, password, and click login button.

Answer:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get("https://example.com/login")

# Enter username
driver.find_element(By.ID, "username").send_keys("testuser")

# Enter password
driver.find_element(By.ID, "password").send_keys("123456")

# Click login
driver.find_element(By.ID, "login").click()

driver.quit()

Important Tip:
Explain locator strategy if asked.


Use Explicit Wait

Very Frequently Asked

Question:
Wait until login button is clickable.

Answer:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)

login_btn = wait.until(
EC.element_to_be_clickable((By.ID, "login"))
)

login_btn.click()

Why this matters:
Most UI failures happen due to synchronization issues.


 Handle Dropdown

Question:
Select value from dropdown.

Answer:

from selenium.webdriver.support.ui import Select

dropdown = Select(driver.find_element(By.ID, "country"))

dropdown.select_by_visible_text("India")

 Handle Alert Popup

Question:
Handle alert popup.

Answer:

alert = driver.switch_to.alert

print(alert.text)

alert.accept()

 Take Screenshot

Very Important Question

Answer:

driver.save_screenshot("login_error.png")

Real usage:
Take screenshot on failure.


Handle Multiple Windows

Question:
Switch to new window.

Answer:

main_window = driver.current_window_handle

for window in driver.window_handles:
if window != main_window:
driver.switch_to.window(window)

Scroll Page

Answer:

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

 Page Object Model (POM) Example

Very Important for Experienced Testers

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()

Why POM matters:
✔ Reusable code
✔ Easy maintenance


 Read Data from Excel (Data-Driven Testing)

Common Interview Question

import openpyxl

wb = openpyxl.load_workbook("data.xlsx")
sheet = wb.active

username = sheet["A2"].value
password = sheet["B2"].value

 What is Page Object Model?

Answer:

Page Object Model (POM) is a design pattern where:

  • Each page has separate class
  • Elements stored in page class
  • Methods created for actions

Benefits:

  • Code reusability
  • Maintainability
  • Less duplication

 What is Hybrid Framework?

Answer:

Hybrid framework combines:

  • Data-driven testing
  • Keyword-driven testing
  • Page Object Model

It provides flexibility and scalability.


Difference Between findElement and findElements?

Answer:

findElementfindElements
Returns single elementReturns list
Throws exception if not foundReturns empty list

What is Stale Element Exception?

Answer:

Occurs when:

  • Page reloads
  • DOM changes
  • Element becomes detached

Solution:

  • Re-locate element
  • Use explicit wait

 How Do You Handle Dynamic Elements?

Answer:

Methods:

  • Use dynamic XPath
  • Use contains()
  • Use starts-with()

Example:

//input[contains(@id,'username')]

 API Testing Scenario (Very Important)

Next I recommend:

👉 Round 3 — API Testing Real-Time Scenarios

Including:

  • POST request testing
  • Token authentication
  • JSON validation
  • Database validation

Reply:

👉 "Start Round 3 API Testing"

and I’ll continue.

Yes

Great 👍 Now let's start Round 3 — API Testing Real-Time Scenarios (Very Important for your profile since you already work with APIs and databases).

These are real interview questions with strong answers you can use directly.


 How Do You Test a POST API? (Very Common)

Question:
How do you test a POST API for user registration?

Answer:

While testing a POST API, I perform the following validations:

Step-by-Step:

1. Verify Request

  • Check correct endpoint URL
  • Validate request body format (JSON/XML)
  • Verify required fields

Example Request:

{
"username": "testuser",
"email": "test@gmail.com",
"password": "Pass@123"
}

2. Verify Response

  • Status Code → 201 Created
  • Response body → Verify success message
  • Validate response structure

Example:

{
"message": "User created successfully",
"userId": 101
}

3. Negative Testing

  • Missing fields
  • Invalid email format
  • Duplicate username

4. Database Validation
Verify record created in database:

SELECT *
FROM users
WHERE username='testuser';

How Do You Validate API Response?

Answer:

I validate:

1. Status Code

Examples:

  • 200 → Success
  • 201 → Created
  • 400 → Bad Request
  • 401 → Unauthorized
  • 500 → Server Error

2. Response Body

  • Validate JSON structure
  • Check required fields
  • Validate data correctness

3. Response Time

Verify response time is acceptable (e.g., < 2 seconds).


4. Headers Validation

Check:

  • Content-Type
  • Authorization

 What is Authentication in API Testing?

Very Frequently Asked

Answer:

Authentication ensures only authorized users access APIs.

Common types:

1. Bearer Token Authentication

Example Header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Steps:

  1. Login API generates token
  2. Use token in Authorization header
  3. Access secured APIs

 Write Test Cases for Login API

Answer:

Positive Cases:

  • Valid username and password
  • Verify status code 200
  • Verify token generated

Negative Cases:

  • Invalid username
  • Invalid password
  • Blank fields

Edge Cases:

  • Special characters
  • Long input values
  • SQL injection attempt

Difference Between PUT and PATCH

Answer:

PUTPATCH
Updates full recordUpdates partial record
Sends complete dataSends only changed fields

 How Do You Handle Token-Based Authentication?

Answer:

Steps:

  1. Call Login API
  2. Extract token from response
  3. Store token in variable
  4. Use token in header for next API calls

Example Flow:

Login API → Get Token → Use Token → Access Secure API

What is JSON?

Answer:

JSON (JavaScript Object Notation) is a lightweight data format used for data exchange between client and server.

Example:

{
"name": "Pushkar",
"role": "Tester"
}

How Do You Perform API Automation?

Answer (Strong Real-Time Answer):

I automate APIs using:

  • Postman (Manual testing)
  • Python requests library (Automation)

Example:

import requests

url = "https://api.example.com/login"

data = {
"username": "testuser",
"password": "123456"
}

response = requests.post(url, json=data)

print(response.status_code)
print(response.json())

What is Mock API?

Answer:

Mock API simulates actual API behavior.

Used when:

  • Backend not ready
  • Integration testing required

Example Tools:

  • Postman
  • Swagger

 Real-Time Scenario Question

Question:
API returns 200 status code but wrong data. What will you do?

Answer:

Steps:

  1. Validate expected response data
  2. Compare with actual response
  3. Check request parameters
  4. Verify backend logs
  5. Raise defect with:
    • Request details
    • Response details
    • Expected result

What is API Regression Testing?

Answer:

API regression testing ensures:

  • Existing APIs still work
  • New changes do not break old APIs

Usually automated.


 What is Rate Limiting?

Answer:

Rate limiting restricts number of API requests in a time period.

Example:

  • 100 requests per minute

Test cases:

  • Send multiple requests
  • Verify API blocks after limit

How Do You Test an API Without UI?

Answer:

I test APIs directly using:

  • API documentation (Swagger)
  • Sending requests via Postman
  • Validating response
  • Verifying backend database

Database + Linux (Highly Important)

Next I'll give:

👉 Round 4 — Database + Linux + Real Project Questions

These are very commonly asked in interviews.

Reply:

👉 "Start Round 4 Database Linux"

and we continue.


Python Basics (Very Important)

What You Learn:

  • Variables
  • If conditions
  • Loops
  • Functions
  • Lists
  • Dictionary
  • File handling

Example — Simple Python Code

name = "Pushkar"

if name == "Pushkar":
print("Welcome Tester")

Very simple rule:

👉 Python reads line by line


Practice Task

Write program:

print("Hello AI Testing")

AI Basics (Simple Language)

What is AI?

AI = Computer that can think and answer like humans.

Example:

You type:

Generate login test cases

AI gives:

List of test cases

What is an AI Agent?

Very simple:

👉 AI Agent = AI + Tools + Decision

Example:

You type:

Test login page

Agent will:

  1. Read requirement
  2. Generate test cases
  3. Run test
  4. Show result

 Prompt Engineering (Very Important)

Prompt = What you ask AI.

Better prompt → Better result.


Bad Prompt 

Generate test cases

Good Prompt 

Generate login test cases including:
- Positive
- Negative
- Edge cases
- Expected results

Practice Prompt

Try:

Generate test cases for ATM withdrawal

Install Required Tools

We use tools like:

  • Python
  • Visual Studio Code
  • OpenAI API

Install Python

Download from:

👉 python.org

Check installation:

python --version

 Your First AI Program

Now we connect Python to AI.


Step 1 — Install Library

pip install openai

Step 2 — First AI Code

from openai import OpenAI

client = OpenAI(api_key="your_api_key")

response = client.responses.create(
model="gpt-4.1-mini",
input="Generate test cases for login page"
)

print(response.output_text)

Output Example

AI prints:

Test Case 1: Valid login
Test Case 2: Invalid password
Test Case 3: Empty username

AI Test Case Generator (Real Testing Use)

Now we build real tester tool.


Code Example

requirement = """
Login page should allow user login
with username and password
"""

prompt = f"""
Generate test cases for:
{requirement}

Include:
Positive
Negative
Edge cases
"""

print(prompt)

AI generates:

Valid login
Invalid login
Password empty

Very useful in real testing.

Now we connect AI with automation.

We use:

  • Selenium

Example Code

from selenium import webdriver

driver = webdriver.Chrome()

driver.get("https://example.com/login")

print("Website Opened")

Now imagine:

AI → Generate test
Selenium → Execute test

That is AI Automation Testing.


 AI API Testing

You already work with APIs — this will help a lot.

We use:

  • Postman
  • Python requests

Example API Code

import requests

url = "https://api.example.com/login"

data = {
"username": "test",
"password": "123"
}

response = requests.post(url, json=data)

print(response.status_code)

AI can generate:

  • Test data
  • Test cases
  • Validation steps

Add Memory to AI Agent

Memory means:

Agent remembers past results.

Example:

Previous login failed
Try different password

Agent learns automatically.


Real Project (Very Important)

Project: AI Testing Assistant


Final Project Flow

Requirement → AI → Test Cases

Selenium

API Testing

Report

This project is resume-ready.

No comments:

Post a Comment

selenium with python

 Certainly! I'll be happy to guide you through learning Selenium step by step. Selenium is a popular open-source framework used for auto...