Wednesday, June 17

Selenium Interview Q&A

 

Selenium Interview Q&A 

Q1. What is Selenium? What are its components?
A: Selenium is an open-source automation testing tool for web applications. Its main components are:

  • Selenium IDE – Record & playback tool.
  • Selenium RC (deprecated) – Older client-server architecture.
  • Selenium WebDriver – Modern, widely used API for browser automation.
  • Selenium Grid – Parallel test execution across multiple machines/browsers.

Q2. Difference between Selenium WebDriver and Selenium RC?
A:

  • WebDriver directly communicates with the browser using native API → faster & more efficient.
  • RC used a server as a middle layer → slower & deprecated.

Q3. Which programming languages are supported by Selenium?
A: Java, Python, C#, Ruby, JavaScript, Kotlin, etc. (Most common: Java & Python).


WebDriver Basics

Q4. How do you launch a browser in Selenium WebDriver?
A (Java Example):

WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");

Q5. Difference between driver.close() and driver.quit()?

  • driver.close() → Closes current active browser window.
  • driver.quit() → Closes all browser windows opened by WebDriver and ends the session.

Q6. How do you locate elements in Selenium?
A: Using locators:

  • id
  • name
  • className
  • tagName
  • linkText / partialLinkText
  • cssSelector
  • xpath

Example:

driver.findElement(By.id("username"));
driver.findElement(By.xpath("//input[@name='q']"));

Waits & Synchronization

Q7. What is the difference between Implicit Wait and Explicit Wait?

  • Implicit Wait → Sets a default waiting time for all elements.
  • Explicit Wait → Waits for a specific condition for a specific element.

Example (Explicit Wait in Java):

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));

Q8. What is Fluent Wait in Selenium?
A: It checks for a condition at regular intervals until timeout. It allows polling frequency & ignoring exceptions.


Practical Questions

Q9. How do you handle dropdowns in Selenium?
A (Java Example):

WebElement dropdown = driver.findElement(By.id("country"));
Select select = new Select(dropdown);
select.selectByVisibleText("India");
select.selectByIndex(2);
select.selectByValue("US");

Q10. How do you handle alerts/popups in Selenium?

Alert alert = driver.switchTo().alert();
alert.accept(); // OK
alert.dismiss(); // Cancel
alert.sendKeys("text"); // For prompt

Q11. How do you handle multiple browser windows?

String mainWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for(String win : allWindows){
driver.switchTo().window(win);
}

Q12. How do you perform mouse hover or drag-and-drop in Selenium?

Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.id("menu"))).perform(); // Hover
actions.dragAndDrop(sourceElement, targetElement).perform(); // Drag & Drop

Advanced Questions

Q13. What is Page Object Model (POM)?
A: A design pattern in Selenium that creates separate classes for each page, storing locators and methods.
It improves reusability & maintainability.


Q14. How do you handle dynamic elements in Selenium?

  • Use XPath with contains(), starts-with()
  • Use CSS selectors with partial attributes
    Example:
driver.findElement(By.xpath("//input[contains(@id,'username')]"));

Q15. How do you capture screenshots in Selenium?

File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("./screenshot.png"));

Q16. How do you run Selenium tests in parallel?

  • Using TestNG parallel=tests or parallel=classes
  • Using Selenium Grid

Q17. What are limitations of Selenium?

  • Supports only web applications (not desktop apps).
  • Cannot automate Captcha, OTP, Barcode directly.
  • No inbuilt reporting → Need tools like TestNG/Allure/Extent Reports.
  • No direct support for image comparison.

Behavioral / Experience-Based

Q18. Tell me about your Selenium framework.
👉 Answer should cover:

  • Framework type: Hybrid / Data-driven / Keyword-driven / POM + TestNG
  • Features used: Maven/Gradle for dependencies, TestNG for test management, Extent/Allure for reporting, Jenkins for CI/CD, Git for version control.

Q19. What challenges did you face in Selenium automation?
Examples you can mention:

  • Handling dynamic elements (solution: smart XPath/CSS).
  • Browser compatibility issues (solution: Selenium Grid).
  • Synchronization issues (solution: Explicit/Fluent waits).
  • Test data management (solution: Excel/CSV/Database integration).

Q20. How do you integrate Selenium with CI/CD?

  • Use Jenkins/GitHub Actions to trigger builds.
  • Configure Maven commands: mvn clean test.
  • Generate reports after test execution.

Intro

Interviewer: Tell me about yourself.
You (Sample Answer):
“I have 2 years of experience in software testing, with a focus on automation using Selenium WebDriver and manual testing. I have worked on web applications across [domain – e.g., healthcare, e-commerce]. My skills include test case design, defect reporting, API testing with Postman, and automation framework development using Selenium with TestNG. I have also integrated my scripts with Jenkins for CI/CD and generated reports using Extent/Allure. I’m comfortable with Agile methodology and actively participated in sprint planning and daily standups.”


Core Selenium

Interviewer: What is Selenium WebDriver, and how is it different from Selenium RC?
You:
“Selenium WebDriver is a tool used to automate browser actions. It communicates directly with the browser using native APIs. Unlike Selenium RC, WebDriver does not need a server in between, which makes it faster and more efficient. Selenium RC is now deprecated, and WebDriver is widely used.”


Interviewer: What locators have you used most often? Which one do you prefer?
You:
“I mostly use XPath and CSS selectors for dynamic elements, but I prefer id or name when available since they are faster and more reliable. If the attributes are dynamic, I use XPath functions like contains(), starts-with(), or CSS with partial matches.”


Interviewer: What is the difference between driver.close() and driver.quit()?
You:
driver.close() closes only the current active browser window, while driver.quit() closes all browser windows opened by WebDriver and ends the session.”


Waits & Synchronization

Interviewer: How do you handle synchronization issues in Selenium?
You:
“I use different types of waits. For general waits, I use implicit wait. For specific conditions, I use explicit wait with WebDriverWait and ExpectedConditions. If I need polling intervals or to ignore exceptions, I use FluentWait. This helps avoid NoSuchElementException or ElementNotInteractableException.”


Practical Coding

Interviewer: Can you write a snippet to select a value from a dropdown?
You (Java Example):

WebElement dropdown = driver.findElement(By.id("country"));
Select select = new Select(dropdown);
select.selectByVisibleText("India");

Interviewer: How would you handle multiple browser windows?
You:

String mainWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for(String win : allWindows){
if(!win.equals(mainWindow)){
driver.switchTo().window(win);
}
}

Framework & Tools

Interviewer: Can you explain your Selenium automation framework?
You:
“My framework is a Hybrid framework combining Page Object Model and Data-Driven approach. I use Maven for dependency management, TestNG for test execution, and Extent/Allure for reporting. I have utilities for reading data from Excel and property files. For CI/CD, I integrated it with Jenkins to trigger test runs automatically. The framework supports parallel execution using TestNG and Selenium Grid.”


Interviewer: How do you manage test data in your automation framework?
You:
“I maintain test data in Excel/CSV files and sometimes in property files for configuration values. I also parameterize tests using TestNG @DataProvider. This helps in reusing the same script with multiple sets of data.”


Challenges

Interviewer: What challenges did you face in Selenium automation, and how did you solve them?
You (Sample Examples):

  • Dynamic elements: Solved using robust XPath with contains() or CSS partial selectors.
  • Page load delays: Used explicit waits like visibilityOfElementLocated.
  • Cross-browser issues: Used Selenium Grid to test in different browsers.
  • Large test execution time: Implemented parallel execution with TestNG.

CI/CD

Interviewer: How do you integrate Selenium tests with Jenkins?
You:
“I created a Jenkins job where I linked our GitHub repository. I configured Maven commands like mvn clean test in the build step. After execution, the job generates Extent/Allure reports, which are published as part of Jenkins build results. This setup ensures automation tests run automatically after every code push.”


Behavioral

Interviewer: Why should we hire you?
You:
“I bring hands-on experience in both manual and automation testing. I have built and executed automation frameworks with Selenium and TestNG, handled challenges with dynamic applications, and worked in Agile teams. With my 2 years of experience, I can quickly contribute to automation efforts, improve test coverage, and help in delivering quality products.”


Must-Practice Selenium Coding Tasks

1. Launch Browser & Open URL

  • Open Chrome/Firefox
  • Navigate to Google
  • Maximize window & print the page title

2. Locating Elements

  • Locate by id, name, class, CSS, XPath
  • Example: search box on Google, login fields on a demo site

3. Login Automation

  • Open login page
  • Enter username, password
  • Click Login button
  • Validate successful login using assert on page title / welcome message

4. Handling Dropdowns (Using Select class)

  • Select by index, value, visible text
  • Example: select “India” from a country dropdown

5. Handling Checkboxes & Radio Buttons

  • Select a checkbox → verify it is selected
  • Select a radio button → verify mutual exclusivity

6. Handling Alerts/Popups

  • Simple alert → accept()
  • Confirmation alert → dismiss()
  • Prompt alert → sendKeys("text")

7. Handling Multiple Windows/Tabs

  • Click link that opens a new tab
  • Switch to child window → perform action
  • Switch back to main window

8. Handling Frames/iFrames

  • Switch to frame by index, name, or WebElement
  • Perform action inside frame
  • Switch back to default content

9. Mouse & Keyboard Actions (Actions Class)

  • Mouse hover (moveToElement)
  • Drag & drop
  • Double click
  • Right click (context click)
  • Send keys with Keys.ENTER

10. Waits (Synchronization)

  • Implicit wait example
  • Explicit wait → wait for element to be clickable
  • Fluent wait → with polling interval

11. Working with Web Tables

  • Find number of rows & columns
  • Read data from a specific cell
  • Iterate through all rows & print values

12. Handling Dynamic Elements

  • Write XPath with contains(), starts-with(), last(), following-sibling
  • Example: selecting a search suggestion from Google auto-suggest list

13. File Upload

  • Use sendKeys("path/to/file") on <input type="file">
  • Or handle OS pop-up with Robot class / AutoIt (if asked)

14. Screenshot Capture

  • Take screenshot on failure
  • Save with dynamic filename (timestamp)

15. Data-Driven Testing (DDT)

  • Use TestNG @DataProvider
  • Read data from Excel (Apache POI)
  • Run the same test with multiple inputs

16. Page Object Model (POM) Implementation

  • Create separate class for each page
  • Store locators & methods inside page classes
  • Use them in test class

17. Parallel Execution

  • Run 2–3 tests in parallel using TestNG XML
  • Example: login test + search test

18. End-to-End Flow Automation

  • Open e-commerce site (like demo.opencart, saucedemo, or Amazon)
  • Search product → Add to cart → Checkout → Validate order success

19. Reporting

  • Integrate Extent Reports or Allure
  • Generate a test execution report

20. Jenkins Integration

  • Create a Maven project
  • Run mvn clean test
  • View test results in Jenkins

Selenium 20 Coding Tasks with Answers (Java + Selenium)


1. Launch Browser & Open URL

WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
System.out.println("Title: " + driver.getTitle());

2. Locating Elements

driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.name("password")).sendKeys("admin123");
driver.findElement(By.className("login-btn")).click();
driver.findElement(By.cssSelector("input[type='text']")).sendKeys("Search");
driver.findElement(By.xpath("//button[text()='Login']")).click();

3. Login Automation

driver.get("https://opensource-demo.orangehrmlive.com/");
driver.findElement(By.id("txtUsername")).sendKeys("Admin");
driver.findElement(By.id("txtPassword")).sendKeys("admin123");
driver.findElement(By.id("btnLogin")).click();

String expected = "Dashboard";
String actual = driver.getTitle();
Assert.assertTrue(actual.contains(expected));

4. Handling Dropdowns

WebElement country = driver.findElement(By.id("country"));
Select select = new Select(country);
select.selectByVisibleText("India");
select.selectByIndex(2);
select.selectByValue("US");

5. Handling Checkboxes & Radio Buttons

WebElement checkbox = driver.findElement(By.id("subscribe"));
checkbox.click();
System.out.println("Checkbox selected: " + checkbox.isSelected());

WebElement radio = driver.findElement(By.id("male"));
radio.click();
System.out.println("Radio selected: " + radio.isSelected());

6. Handling Alerts

Alert alert = driver.switchTo().alert();
alert.accept(); // OK
alert.dismiss(); // Cancel
alert.sendKeys("Hello"); // For prompt alerts

7. Handling Multiple Windows

String main = driver.getWindowHandle();
driver.findElement(By.linkText("Open New Window")).click();

for(String win : driver.getWindowHandles()){
if(!win.equals(main)){
driver.switchTo().window(win);
System.out.println("Child window title: " + driver.getTitle());
driver.close();
}
}
driver.switchTo().window(main);

8. Handling Frames/iFrames

driver.switchTo().frame("frame1");
driver.findElement(By.id("username")).sendKeys("testUser");
driver.switchTo().defaultContent();

9. Mouse & Keyboard Actions

Actions actions = new Actions(driver);
WebElement menu = driver.findElement(By.id("menu"));
actions.moveToElement(menu).perform(); // Hover

WebElement src = driver.findElement(By.id("source"));
WebElement dest = driver.findElement(By.id("target"));
actions.dragAndDrop(src, dest).perform();

actions.doubleClick(driver.findElement(By.id("doubleClickBtn"))).perform();
actions.contextClick(driver.findElement(By.id("rightClickBtn"))).perform();
actions.sendKeys(Keys.ENTER).perform();

10. Waits

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
WebElement el = wait.until(ExpectedConditions.elementToBeClickable(By.id("login")));

Wait<WebDriver> fwait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
WebElement ele = fwait.until(d -> d.findElement(By.id("username")));

11. Web Tables

List<WebElement> rows = driver.findElements(By.xpath("//table[@id='data']/tbody/tr"));
List<WebElement> cols = driver.findElements(By.xpath("//table[@id='data']/thead/tr/th"));

System.out.println("Rows: " + rows.size());
System.out.println("Cols: " + cols.size());

for(WebElement row : rows){
System.out.println(row.getText());
}

12. Handling Dynamic Elements

driver.findElement(By.xpath("//input[contains(@id,'user')]")).sendKeys("test");
driver.findElement(By.cssSelector("div[class*='login']")).click();
driver.findElement(By.xpath("//button[starts-with(@id,'btn_')]")).click();

13. File Upload

WebElement upload = driver.findElement(By.id("fileUpload"));
upload.sendKeys("C:\\Users\\Pushkar\\Documents\\testfile.txt");

14. Screenshot Capture

File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File dest = new File("screenshot_" + System.currentTimeMillis() + ".png");
Files.copy(src.toPath(), dest.toPath());

15. Data-Driven Testing (TestNG + DataProvider)

@DataProvider(name="loginData")
public Object[][] getData(){
return new Object[][] { {"Admin","admin123"}, {"User","user123"} };
}

@Test(dataProvider="loginData")
public void loginTest(String user, String pass){
driver.findElement(By.id("username")).sendKeys(user);
driver.findElement(By.id("password")).sendKeys(pass);
driver.findElement(By.id("login")).click();
}

16. Page Object Model (POM)

// LoginPage.java
public class LoginPage {
WebDriver driver;
By username = By.id("username");
By password = By.id("password");
By loginBtn = By.id("login");

public LoginPage(WebDriver driver){ this.driver = driver; }

public void login(String user, String pass){
driver.findElement(username).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginBtn).click();
}
}

// TestClass.java
LoginPage lp = new LoginPage(driver);
lp.login("Admin","admin123");

17. Parallel Execution (TestNG XML)

<suite name="ParallelTests" parallel="tests" thread-count="2">
<test name="ChromeTest">
<parameter name="browser" value="chrome"/>
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
<test name="FirefoxTest">
<parameter name="browser" value="firefox"/>
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
</suite>

18. End-to-End Flow

driver.get("https://www.saucedemo.com/");
driver.findElement(By.id("user-name")).sendKeys("standard_user");
driver.findElement(By.id("password")).sendKeys("secret_sauce");
driver.findElement(By.id("login-button")).click();

driver.findElement(By.xpath("//div[text()='Sauce Labs Backpack']")).click();
driver.findElement(By.id("add-to-cart-sauce-labs-backpack")).click();
driver.findElement(By.className("shopping_cart_link")).click();

driver.findElement(By.id("checkout")).click();
driver.findElement(By.id("first-name")).sendKeys("John");
driver.findElement(By.id("last-name")).sendKeys("Doe");
driver.findElement(By.id("postal-code")).sendKeys("12345");
driver.findElement(By.id("continue")).click();
driver.findElement(By.id("finish")).click();

19. Reporting (Extent Reports Example)

ExtentReports extent = new ExtentReports();
ExtentSparkReporter spark = new ExtentSparkReporter("report.html");
extent.attachReporter(spark);

ExtentTest test = extent.createTest("Login Test");
test.pass("Opened browser");
test.fail("Login failed");

extent.flush();

20. Jenkins Integration

  • Push project to GitHub (Maven + TestNG).
  • Jenkins → Create job → Configure Git repo.
  • In Build Step → use:
mvn clean test

  • Post-build → Publish HTML/Extent reports.

Project Structure

selenium-testng-framework/
│── pom.xml
│── testng.xml
│── src
│ ├── main
│ │ └── java
│ │ └── pages # Page Object Model (POM) classes
│ │ └── LoginPage.java
│ └── test
│ └── java
│ ├── tests # Test classes
│ │ └── LoginTest.java
│ └── utils # Utility classes
│ └── ExtentManager.java
│── reports/ # Auto-generated test reports

📄 pom.xml (Dependencies)

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pushkar.selenium</groupId>
<artifactId>selenium-testng-framework</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<!-- Selenium -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.25.0</version>
</dependency>

<!-- TestNG -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.10.2</version>
<scope>test</scope>
</dependency>

<!-- Extent Reports -->
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>5.1.1</version>
</dependency>

<!-- WebDriver Manager (auto driver setup) -->
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.9.2</version>
</dependency>
</dependencies>

<build>
<plugins>
<!-- Maven Compiler Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>

<!-- Maven Surefire Plugin for TestNG -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
</project>

📄 testng.xml

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Selenium Suite" parallel="false">
<test name="Login Test">
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
</suite>

📄 pages/LoginPage.java

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage {
WebDriver driver;

By username = By.id("user-name");
By password = By.id("password");
By loginBtn = By.id("login-button");

public LoginPage(WebDriver driver) {
this.driver = driver;
}

public void login(String user, String pass) {
driver.findElement(username).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginBtn).click();
}
}

📄 utils/ExtentManager.java

package utils;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentSparkReporter;

public class ExtentManager {
private static ExtentReports extent;

public static ExtentReports getInstance() {
if (extent == null) {
ExtentSparkReporter reporter = new ExtentSparkReporter("reports/extent-report.html");
reporter.config().setReportName("Automation Test Report");
reporter.config().setDocumentTitle("Selenium Framework Report");

extent = new ExtentReports();
extent.attachReporter(reporter);
}
return extent;
}
}

📄 tests/LoginTest.java

package tests;

import org.openqa.selenium.WebDriver;
import org.testng.annotations.*;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.chrome.ChromeDriver;
import pages.LoginPage;
import utils.ExtentManager;

public class LoginTest {
WebDriver driver;
ExtentReports extent;
ExtentTest test;

@BeforeSuite
public void setupReport() {
extent = ExtentManager.getInstance();
}

@BeforeMethod
public void setup() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.saucedemo.com/");
}

@Test
public void loginTest() {
test = extent.createTest("Login Test");
LoginPage lp = new LoginPage(driver);
lp.login("standard_user", "secret_sauce");
String title = driver.getTitle();

if (title.contains("Swag Labs")) {
test.log(Status.PASS, "Login successful");
} else {
test.log(Status.FAIL, "Login failed");
}
}

@AfterMethod
public void tearDown() {
driver.quit();
}

@AfterSuite
public void flushReport() {
extent.flush();
}
}

Run Instructions

  1. Clone project from GitHub (or create new Maven project).
  2. Run tests with:

    mvn clean test

  3. Open report:

    reports/extent-report.html

    Using Excel (Apache POI)

    You can read data from Excel and pass it to TestNG @DataProvider

    ✅ Step 1: Add dependency in pom.xml

    <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.3.0</version>
    </dependency>

    ✅ Step 2: Create Excel File

    📄 TestData.xlsx → Sheet Name: LoginData

    UsernamePassword
    standard_usersecret_sauce
    locked_out_usersecret_sauce
    problem_usersecret_sauce

    ✅ Step 3: Utility Class to Read Excel

    package utils;

    import java.io.FileInputStream;
    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;

    public class ExcelUtils {

    public static Object[][] getExcelData(String filePath, String sheetName) {
    Object[][] data = null;
    try (FileInputStream fis = new FileInputStream(filePath);
    Workbook workbook = new XSSFWorkbook(fis)) {
    Sheet sheet = workbook.getSheet(sheetName);
    int rowCount = sheet.getPhysicalNumberOfRows();
    int colCount = sheet.getRow(0).getPhysicalNumberOfCells();

    data = new Object[rowCount - 1][colCount];
    for (int i = 1; i < rowCount; i++) {
    Row row = sheet.getRow(i);
    for (int j = 0; j < colCount; j++) {
    data[i - 1][j] = row.getCell(j).getStringCellValue();
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return data;
    }
    }

    ✅ Step 4: Test Class with DataProvider

    package tests;

    import org.testng.annotations.DataProvider;
    import org.testng.annotations.Test;
    import utils.ExcelUtils;
    import io.github.bonigarcia.wdm.WebDriverManager;
    import org.openqa.selenium.*;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class ExcelDataDrivenTest {

    @DataProvider(name = "excelData")
    public Object[][] getData() {
    return ExcelUtils.getExcelData("src/test/resources/TestData.xlsx", "LoginData");
    }

    @Test(dataProvider = "excelData")
    public void loginTest(String username, String password) {
    WebDriverManager.chromedriver().setup();
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://www.saucedemo.com/");

    driver.findElement(By.id("user-name")).sendKeys(username);
    driver.findElement(By.id("password")).sendKeys(password);
    driver.findElement(By.id("login-button")).click();

    System.out.println("Login test done for user: " + username);
    driver.quit();
    }
    }

    Using CSV File

    ✅ Step 1: Add OpenCSV dependency

    <dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.9</version>
    </dependency>

    ✅ Step 2: Sample CSV file – login.csv

    username,password
    standard_user,secret_sauce
    locked_out_user,secret_sauce
    problem_user,secret_sauce

    ✅ Step 3: Read CSV and Use in TestNG

    package tests;

    import com.opencsv.CSVReader;
    import org.testng.annotations.DataProvider;
    import org.testng.annotations.Test;
    import java.io.FileReader;
    import java.util.List;
    import io.github.bonigarcia.wdm.WebDriverManager;
    import org.openqa.selenium.*;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class CSVDataDrivenTest {

    @DataProvider(name = "csvData")
    public Object[][] getData() throws Exception {
    CSVReader reader = new CSVReader(new FileReader("src/test/resources/login.csv"));
    List<String[]> allData = reader.readAll();
    Object[][] data = new Object[allData.size() - 1][2];

    for (int i = 1; i < allData.size(); i++) {
    data[i - 1][0] = allData.get(i)[0];
    data[i - 1][1] = allData.get(i)[1];
    }
    return data;
    }

    @Test(dataProvider = "csvData")
    public void loginTest(String username, String password) {
    WebDriverManager.chromedriver().setup();
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.saucedemo.com/");
    driver.findElement(By.id("user-name")).sendKeys(username);
    driver.findElement(By.id("password")).sendKeys(password);
    driver.findElement(By.id("login-button")).click();
    System.out.println("CSV login done for: " + username);
    driver.quit();
    }
    }

    📊 Benefits of DDT

    BenefitDescription
    ✅ ReusabilityOne script, multiple data sets
    ✅ MaintainabilityData stored outside the script
    ✅ ScalabilityEasily add new data without editing code
    ✅ Automation CoverageQuickly validate different user scenarios

    Interview Tip:

    Common Question: “How do you implement Data-Driven Testing in Selenium?”
    Sample Answer:

    “I implement data-driven testing using TestNG’s DataProvider or Apache POI for Excel-based data.

    I externalize test data in Excel sheets, fetch them dynamically at runtime, and pass them

    into my test methods. This helps me run the same test with multiple input combinations without

    modifying the test logic.”

    Perfect 👍 Pushkar — now let’s go one level higher with 20 Selenium Scenario-Based Practical Q&A (these are common in interviews for QA Automation roles, especially 1–3 years experience).

    Each one includes a real-world situation + best-practice answer or code snippet

    🔹 20 Selenium Scenario-Based Interview Questions & Answers

    1️⃣ How do you handle a hidden element in Selenium?

    Hidden elements are not visible in the DOM for user interaction.
    To interact, you can use JavaScriptExecutor:

    WebElement hiddenButton = driver.findElement(By.id("hiddenBtn"));
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].click();", hiddenButton);

    2️⃣ How do you verify that an element is displayed on a webpage?

    boolean isDisplayed = driver.findElement(By.id("logo")).isDisplayed();
    if(isDisplayed) {
    System.out.println("Logo is visible");
    }

    3️⃣ How to handle dynamic elements whose IDs change every time?

    Use contains() or starts-with() in XPath.

    driver.findElement(By.xpath("//input[contains(@id, 'user')]"));

    4️⃣ How do you verify the title of a webpage?

    String actualTitle = driver.getTitle();
    Assert.assertEquals(actualTitle, "Expected Page Title");

    5️⃣ How do you scroll down a webpage in Selenium?

    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("window.scrollBy(0,500)");

    6️⃣ How to handle a popup window or alert?

    Alert alert = driver.switchTo().alert();
    System.out.println(alert.getText());
    alert.accept();

    7️⃣ How to handle multiple browser windows?

    String parentWindow = driver.getWindowHandle();
    for(String handle : driver.getWindowHandles()) {
    if(!handle.equals(parentWindow)) {
    driver.switchTo().window(handle);
    }
    }

    8️⃣ How to verify a broken link on a webpage?

    List<WebElement> links = driver.findElements(By.tagName("a"));
    for (WebElement link : links) {
    String url = link.getAttribute("href");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.connect();
    if(conn.getResponseCode() >= 400) {
    System.out.println(url + " is broken");
    }
    }

    9️⃣ How to handle a dropdown without using the Select class?

    driver.findElement(By.id("dropdown")).click();
    driver.findElement(By.xpath("//option[text()='Option 2']")).click();

    🔟 How do you upload a file in Selenium?

    Use sendKeys() with file path (no need for AutoIt or Robot).

    driver.findElement(By.id("fileUpload")).sendKeys("C:\\Users\\Pushkar\\resume.pdf");

    11️⃣ How do you download a file in Selenium?

    You can set browser preferences using ChromeOptions or FirefoxProfile.

    HashMap<String, Object> prefs = new HashMap<>();
    prefs.put("download.default_directory", "C:\\Downloads");
    ChromeOptions options = new ChromeOptions();
    options.setExperimentalOption("prefs", prefs);
    WebDriver driver = new ChromeDriver(options);

    12️⃣ How to take a screenshot when a test fails?

    File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(src, new File("./Screenshots/failure.png"));

    13️⃣ How to verify text present on the webpage?

    String bodyText = driver.findElement(By.tagName("body")).getText();
    Assert.assertTrue(bodyText.contains("Welcome, Pushkar"));

    14️⃣ How do you perform mouse hover action?

    Actions actions = new Actions(driver);
    actions.moveToElement(driver.findElement(By.id("menu"))).perform();

    15️⃣ How do you perform double-click or right-click actions?

    Actions actions = new Actions(driver);
    actions.doubleClick(element).perform();
    actions.contextClick(element).perform();

    16️⃣ How to handle an iFrame in Selenium?

    driver.switchTo().frame("frameName");
    // perform actions
    driver.switchTo().defaultContent();

    17️⃣ How do you wait for an element to be clickable?

    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    WebElement btn = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
    btn.click();

    18️⃣ How do you verify if a checkbox is selected or not?

    WebElement checkbox = driver.findElement(By.id("subscribe"));
    if(!checkbox.isSelected()) {
    checkbox.click();
    }

    19️⃣ How to capture tooltip text in Selenium?

    WebElement tooltip = driver.findElement(By.id("tooltip"));
    String tooltipText = tooltip.getAttribute("title");
    System.out.println("Tooltip text is: " + tooltipText);

    20️⃣ How do you handle stale element reference exceptions?

    Re-locate the element before performing an action.

    try {
    driver.findElement(By.id("username")).click();
    } catch (StaleElementReferenceException e) {
    driver.findElement(By.id("username")).click();
    }

    🧠 Bonus Interview Tip

    💬 If you get a scenario question like:

    “How do you test login functionality when credentials come from an Excel file?”

    You can confidently answer:

    “I perform data-driven testing using TestNG’s @DataProvider and read data using Apache POI. Each dataset (username/password) runs as a separate test iteration.”


    Would you like me to give you a set of 20 Selenium + TestNG combined interview Q&A next (like @BeforeTest, @DataProvider, assertions, priorities, dependencies, etc.) — these are also very common for QA automation interviews?

    Python program for automation testing

    Great 👍 Since you're preparing for automation testing interviews, here are Python programs commonly used in automation testing (especially with Selenium + Python). These are simple to intermediate level and frequently asked in QA interviews.


    🐍 Python Programs for Automation Testing (Interview Focus)


    1️⃣ Launch Browser and Open Website

    from selenium import webdriver

    # Launch Chrome browser
    driver = webdriver.Chrome()

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

    # Maximize window
    driver.maximize_window()

    # Close browser
    driver.quit()

    👉 Interview Use: Basic Selenium Python script


    2️⃣ Login Automation Script

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

    driver = webdriver.Chrome()

    driver.get("https://www.saucedemo.com/")

    # Enter username
    driver.find_element(By.ID, "user-name").send_keys("standard_user")

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

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

    time.sleep(3)

    driver.quit()

    👉 Very common real-time login automation example


    3️⃣ Take Screenshot

    from selenium import webdriver

    driver = webdriver.Chrome()

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

    # Take screenshot
    driver.save_screenshot("homepage.png")

    driver.quit()

    👉 Used in failure handling


    4️⃣ Handle Dropdown

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import Select

    driver = webdriver.Chrome()

    driver.get("https://www.facebook.com/")

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

    dropdown.select_by_visible_text("10")

    driver.quit()

    5️⃣ Wait for Element (Explicit Wait)

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

    driver = webdriver.Chrome()

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

    wait = WebDriverWait(driver, 10)

    search_box = wait.until(
    EC.presence_of_element_located((By.NAME, "q"))
    )

    search_box.send_keys("Selenium Python")

    driver.quit()

    👉 Very important interview question


    6️⃣ Read Data from Excel (Data-Driven Testing)

    import openpyxl

    # Load workbook
    workbook = openpyxl.load_workbook("testdata.xlsx")

    sheet = workbook.active

    # Read data
    username = sheet.cell(row=2, column=1).value
    password = sheet.cell(row=2, column=2).value

    print(username, password)

    👉 Used in Data-Driven Framework


    7️⃣ Loop Through Multiple Test Data

    import openpyxl

    workbook = openpyxl.load_workbook("testdata.xlsx")
    sheet = workbook.active

    for row in range(2, sheet.max_row + 1):
    username = sheet.cell(row=row, column=1).value
    password = sheet.cell(row=row, column=2).value

    print(username, password)

    8️⃣ Handle Alerts

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

    driver = webdriver.Chrome()

    driver.get("https://demoqa.com/alerts")

    driver.find_element(By.ID, "alertButton").click()

    alert = driver.switch_to.alert

    print(alert.text)

    alert.accept()

    driver.quit()

    9️⃣ Handle Multiple Windows

    from selenium import webdriver

    driver = webdriver.Chrome()

    driver.get("https://www.naukri.com/")

    parent = driver.current_window_handle

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

    driver.switch_to.window(parent)

    driver.quit()

    🔟 PyTest Test Example

    def test_addition():
    a = 5
    b = 10
    assert a + b == 15

    👉 Used in Python automation frameworks


    1️⃣1️⃣ Reverse a String (Python Basic — Frequently Asked)

    text = "selenium"

    reverse = text[::-1]

    print(reverse)

    Output:

    muineles

    1️⃣2️⃣ Count Occurrence of Characters

    text = "automation"

    count = {}

    for char in text:
    if char in count:
    count[char] += 1
    else:
    count[char] = 1

    print(count)

    1️⃣3️⃣ Find Duplicate Elements in List

    numbers = [1,2,3,4,2,5,3]

    duplicates = []

    for num in numbers:
    if numbers.count(num) > 1:
    if num not in duplicates:
    duplicates.append(num)

    print(duplicates)

    Output:

    [2, 3]

    1️⃣4️⃣ Read Text File

    file = open("test.txt", "r")

    content = file.read()

    print(content)

    file.close()

    1️⃣5️⃣ Write Logs into File

    file = open("log.txt", "w")

    file.write("Test Execution Started")

    file.close()

    ⭐ Most Important Python Topics for Automation QA

    Focus on these for interviews:

    ✅ Selenium with Python
    ✅ PyTest
    ✅ openpyxl (Excel handling)
    ✅ Loops
    ✅ Functions
    ✅ Exception Handling
    ✅ File Handling
    ✅ String Handling
    ✅ List & Dictionary


    🚀 Next Best Step

    PyTest Framework
    Page Object Model (Python)
    API Testing using Python requests
    Hybrid Framework in Python


    Would you like me to create a complete Selenium Python framework (POM + PyTest + Excel + Reports) step-by-step?
    That would be very useful for automation QA interviews and real projects.

    Yes

    Great 👍 Pushkar — now I’ll build a Complete Selenium Python Framework (POM + PyTest + Excel + Reports) step-by-step.
    This is very useful for automation QA interviews and also matches your experience in automation testing.

    🚀 Selenium Python Framework (POM + PyTest + Excel + Reports)

    build a real-world automation framework with:

    ✅ Selenium
    ✅ PyTest
    ✅ Page Object Model (POM)
    ✅ Excel Data Driven Testing
    ✅ Screenshot on Failure
    ✅ HTML Report

    🧱 Step 1 — Install Required Packages

    Run in terminal:

    pip install selenium
    pip install pytest
    pip install openpyxl
    pip install pytest-html
    pip install webdriver-manager

    🧱 Step 2 — Project Folder Structure

    Create this structure:

    selenium_python_framework/


    ├── pages/
    │ └── login_page.py

    ├── tests/
    │ └── test_login.py

    ├── utils/
    │ ├── excel_utils.py
    │ └── screenshot_utils.py

    ├── testdata/
    │ └── testdata.xlsx

    ├── reports/

    ├── conftest.py

    └── pytest.ini

    This is a standard industry structure.

    🧱 Step 3 — Create Excel Test Data

    📄 testdata/testdata.xlsx

    UsernamePassword
    standard_usersecret_sauce
    locked_out_usersecret_sauce

    🧱 Step 4 — Excel Utility

    📄 utils/excel_utils.py

    import openpyxl

    def read_excel(file_path, sheet_name):

    workbook = openpyxl.load_workbook(file_path)

    sheet = workbook[sheet_name]

    data = []

    for row in sheet.iter_rows(min_row=2, values_only=True):
    data.append(row)

    return data

    🧱 Step 5 — Screenshot Utility

    📄 utils/screenshot_utils.py

    import os
    from datetime import datetime

    def take_screenshot(driver, test_name):

    folder = "reports/screenshots"

    if not os.path.exists(folder):
    os.makedirs(folder)

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    file_name = f"{folder}/{test_name}_{timestamp}.png"

    driver.save_screenshot(file_name)

    return file_name

    🧱 Step 6 — Page Object Model (Login Page)

    📄 pages/login_page.py

    from selenium.webdriver.common.by import By

    class LoginPage:

    def __init__(self, driver):
    self.driver = driver

    username = (By.ID, "user-name")
    password = (By.ID, "password")
    login_button = (By.ID, "login-button")

    def login(self, user, pwd):

    self.driver.find_element(*self.username).send_keys(user)

    self.driver.find_element(*self.password).send_keys(pwd)

    self.driver.find_element(*self.login_button).click()

    def is_login_successful(self):

    return "inventory" in self.driver.current_url

    🧱 Step 7 — WebDriver Setup (Fixture)

    📄 conftest.py

    import pytest
    from selenium import webdriver
    from webdriver_manager.chrome import ChromeDriverManager
    from selenium.webdriver.chrome.service import Service

    @pytest.fixture
    def driver():

    service = Service(ChromeDriverManager().install())

    driver = webdriver.Chrome(service=service)

    driver.maximize_window()

    driver.get("https://www.saucedemo.com/")

    yield driver

    driver.quit()

    This is PyTest fixture setup.

    🧱 Step 8 — Test Script (Data Driven)

    📄 tests/test_login.py

    import pytest

    from pages.login_page import LoginPage
    from utils.excel_utils import read_excel
    from utils.screenshot_utils import take_screenshot

    file_path = "testdata/testdata.xlsx"

    data = read_excel(file_path, "Sheet1")


    @pytest.mark.parametrize("username,password", data)

    def test_login(driver, username, password):

    login_page = LoginPage(driver)

    login_page.login(username, password)

    if not login_page.is_login_successful():

    take_screenshot(driver, username)

    assert login_page.is_login_successful()

    🧱 Step 9 — PyTest Configuration

    📄 pytest.ini

    [pytest]

    addopts = --html=reports/report.html --self-contained-html

    testpaths = tests

    This creates an HTML report automatically.

    🧱 Step 10 — Run the Framework

    Run this command:

    pytest

    Output:

    reports/report.html
    reports/screenshots/

    Open:

    reports/report.html

    You’ll see:

    ✅ Pass / Fail
    📸 Screenshots
    📊 Test Results


    🧠 Interview Questions You Can Answer Using This Framework

    Very important for your profile.

    Q1 — What framework have you built in Selenium Python?

    Answer:

    I developed a Selenium Python automation framework using PyTest and Page Object Model. It supports data-driven testing using Excel, includes screenshot capture on failures, and generates HTML reports using pytest-html.

    Q2 — What design pattern did you use?

    Answer:

    I used the Page Object Model (POM) design pattern to separate test logic from page locators and actions.

    Q3 — How do you perform data-driven testing?

    Answer:

    I read test data from Excel using openpyxl and pass the data to tests using pytest parametrize.

    Q4 — How do you handle failures?

    Answer:

    I capture screenshots automatically when a test fails using a screenshot utility function. 

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...