Popular Searches
Popular Course Categories
Popular Courses

Selenium Practical Questions

Selenium Practical Questions

Job Preparation

Selenium Practical Questions

Selenium Practical Questions are hands-on problems designed to test a learner's ability to apply Selenium WebDriver, Java, TestNG, Page Object Model, waits, locators, browser interactions, and automation framework concepts in real-world testing scenarios.

Practical Selenium questions are important because automation testing requires more than knowing definitions. A tester should be able to write maintainable automation code, identify web elements, handle synchronization, work with dynamic applications, debug failures, manage browser sessions, validate results, and build reusable test components.

These practical questions cover common Selenium automation scenarios including browser handling, locators, forms, dropdowns, alerts, frames, windows, waits, screenshots, tables, JavaScript, file handling, TestNG, Data Providers, POM, assertions, exception handling, and framework design.

Course Resource: Selenium Training | Register for Course Demo


1. Open a Browser Using Selenium

One of the first practical Selenium tasks is to launch a browser and navigate to a website.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class BrowserTest {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.manage().window().maximize();

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

        driver.quit();

    }

}

The WebDriver object controls the browser, while get() navigates to the requested URL.


2. Write a Test to Verify Page Title

The page title can be retrieved using getTitle().

String actualTitle = driver.getTitle();

 

System.out.println("Page Title: " + actualTitle);

 

Assert.assertEquals(actualTitle, "Example Domain");

This type of validation confirms that the expected page has been loaded.


3. Find an Element Using ID

The ID locator is generally preferred when the application provides a stable and unique ID.

WebElement username = driver.findElement(By.id("username"));

username.sendKeys("admin");


4. Find an Element Using Name

WebElement password = driver.findElement(By.name("password"));

password.sendKeys("admin123");


5. Find an Element Using Class Name

WebElement loginButton = driver.findElement(By.className("login-button"));

loginButton.click();

The class name should identify the intended element without including invalid compound class syntax.


6. Find an Element Using CSS Selector

CSS selectors are useful when an element does not have a convenient unique ID or name.

WebElement username = driver.findElement(

    By.cssSelector("#username")

);

 

username.sendKeys("admin");

Another example is:

driver.findElement(

    By.cssSelector("input[name='email']")

).sendKeys("[email protected]");


7. Find an Element Using XPath

XPath is commonly used for complex or dynamic element identification.

WebElement loginButton = driver.findElement(

    By.xpath("//button[@id='loginButton']")

);

 

loginButton.click();


8. Handle a Login Form

A common Selenium practical question is to automate a complete login workflow.

driver.findElement(By.id("username"))

      .sendKeys("admin");

 

driver.findElement(By.id("password"))

      .sendKeys("admin123");

 

driver.findElement(By.id("loginButton"))

      .click();

A real test should additionally verify the expected result after clicking the login button.


9. Verify Whether an Element Is Displayed

The isDisplayed() method checks whether an element is displayed on the page.

WebElement message = driver.findElement(

    By.id("successMessage")

);

 

if (message.isDisplayed()) {

    System.out.println("Success message is displayed");

}


10. Verify Whether an Element Is Enabled

WebElement button = driver.findElement(

    By.id("submitButton")

);

 

if (button.isEnabled()) {

    System.out.println("Button is enabled");

}


11. Verify Whether a Checkbox Is Selected

WebElement checkbox = driver.findElement(

    By.id("terms")

);

 

if (!checkbox.isSelected()) {

    checkbox.click();

}


12. Select a Checkbox

Checkboxes can be selected by clicking them when they are not already selected.

WebElement checkbox = driver.findElement(

    By.id("subscribe")

);

 

if (!checkbox.isSelected()) {

    checkbox.click();

}


13. Handle Radio Buttons

WebElement maleRadio = driver.findElement(

    By.id("male")

);

 

if (!maleRadio.isSelected()) {

    maleRadio.click();

}


14. Handle a Dropdown

The Selenium Select class can be used for standard HTML select elements.

import org.openqa.selenium.support.ui.Select;

 

WebElement country = driver.findElement(

    By.id("country")

);

 

Select select = new Select(country);

 

select.selectByVisibleText("India");


15. Select Dropdown by Value

Select select = new Select(

    driver.findElement(By.id("country"))

);

 

select.selectByValue("IN");


16. Select Dropdown by Index

Select select = new Select(

    driver.findElement(By.id("country"))

);

 

select.selectByIndex(2);


17. Get All Dropdown Options

Select select = new Select(

    driver.findElement(By.id("country"))

);

 

List<WebElement> options = select.getOptions();

 

for (WebElement option : options) {

    System.out.println(option.getText());

}


18. Handle JavaScript Alert

JavaScript alerts can be handled using the Selenium Alert interface.

Alert alert = driver.switchTo().alert();

 

System.out.println(alert.getText());

 

alert.accept();


19. Dismiss a Confirmation Alert

Alert alert = driver.switchTo().alert();

 

alert.dismiss();


20. Enter Text into a Prompt

Alert alert = driver.switchTo().alert();

 

alert.sendKeys("Test User");

alert.accept();


21. Handle an Iframe

Before interacting with an element inside an iframe, Selenium must switch into the appropriate frame.

driver.switchTo().frame("paymentFrame");

 

driver.findElement(By.id("cardNumber"))

      .sendKeys("4111111111111111");

 

driver.switchTo().defaultContent();


22. Handle a Frame Using WebElement

WebElement frame = driver.findElement(

    By.id("frame1")

);

 

driver.switchTo().frame(frame);

 

driver.findElement(By.id("username"))

      .sendKeys("admin");

 

driver.switchTo().defaultContent();


23. Handle Nested Frames

For nested frames, Selenium needs to switch through the frame hierarchy.

driver.switchTo().frame("outerFrame");

driver.switchTo().frame("innerFrame");

 

driver.findElement(By.id("submit"))

      .click();

 

driver.switchTo().defaultContent();


24. Switch Between Browser Windows

Selenium provides getWindowHandle() and getWindowHandles() for managing browser windows or tabs.

String parentWindow = driver.getWindowHandle();

 

Set<String> windows = driver.getWindowHandles();

 

for (String window : windows) {

    if (!window.equals(parentWindow)) {

        driver.switchTo().window(window);

        break;

    }

}


25. Get All Window Handles

Set<String> handles = driver.getWindowHandles();

 

for (String handle : handles) {

    System.out.println(handle);

}


26. Close a Specific Window

String parent = driver.getWindowHandle();

 

for (String handle : driver.getWindowHandles()) {

    if (!handle.equals(parent)) {

        driver.switchTo().window(handle);

        driver.close();

    }

}

 

driver.switchTo().window(parent);


27. Difference Between close() and quit()

MethodPurpose
close()Closes the currently active browser window or tab.
quit()Closes all browser windows associated with the WebDriver session and ends the session.


28. Implement an Explicit Wait

Explicit waits allow a test to wait for a specific condition instead of using fixed delays.

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement loginButton = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("loginButton")

    )

);

 

loginButton.click();


29. Wait for an Element to Be Visible

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement message = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("successMessage")

    )

);

 

System.out.println(message.getText());


30. Wait for an Element to Exist

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement element = wait.until(

    ExpectedConditions.presenceOfElementLocated(

        By.id("username")

    )

);


31. Handle Dynamic Web Elements

Dynamic elements may have attributes that change between executions. Stable attributes, relative XPath expressions, CSS selectors, or parent-child relationships can be used to identify them.

WebElement button = driver.findElement(

    By.xpath("//button[contains(@class,'submit')]")

);

 

button.click();

Another example is:

driver.findElement(

    By.xpath("//label[normalize-space()='Username']/following::input[1]")

).sendKeys("admin");


32. Handle StaleElementReferenceException

A stale element occurs when the DOM changes and the previously located WebElement is no longer attached to the current DOM.

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement element = wait.until(

    ExpectedConditions.refreshed(

        ExpectedConditions.elementToBeClickable(

            By.id("submit")

        )

    )

);

 

element.click();

Re-locating the element after a DOM refresh is often preferable to reusing an outdated WebElement reference.


33. Take a Screenshot

Screenshots are useful when debugging failures and documenting test execution.

File source = ((TakesScreenshot) driver)

    .getScreenshotAs(OutputType.FILE);

 

File destination = new File("screenshots/home.png");

 

Files.copy(

    source.toPath(),

    destination.toPath(),

    StandardCopyOption.REPLACE_EXISTING

);


34. Take a Screenshot on Test Failure

In a TestNG framework, screenshots can be captured when a test fails by using listeners or failure-handling utilities.

@Override

public void onTestFailure(ITestResult result) {

    WebDriver driver = DriverManager.getDriver();

    if (driver != null) {

        captureScreenshot(

            driver,

            result.getName()

        );

    }

}

A listener-based design keeps failure handling separate from individual test methods.


35. Get Text from an Element

String text = driver.findElement(

    By.id("message")

).getText();

 

System.out.println(text);


36. Get an Attribute Value

String value = driver.findElement(

    By.id("email")

).getAttribute("value");

 

System.out.println(value);


37. Clear an Input Field

WebElement searchBox = driver.findElement(

    By.id("search")

);

 

searchBox.clear();

searchBox.sendKeys("Laptop");


38. Press Enter Using Keyboard Actions

WebElement searchBox = driver.findElement(

    By.id("search")

);

 

searchBox.sendKeys(Keys.ENTER);


39. Perform Mouse Hover

Actions actions = new Actions(driver);

 

WebElement menu = driver.findElement(

    By.id("productsMenu")

);

 

actions.moveToElement(menu).perform();


40. Perform Double Click

Actions actions = new Actions(driver);

 

WebElement element = driver.findElement(

    By.id("item")

);

 

actions.doubleClick(element).perform();


41. Perform Right Click

Actions actions = new Actions(driver);

 

WebElement element = driver.findElement(

    By.id("contextMenu")

);

 

actions.contextClick(element).perform();


42. Perform Drag and Drop

Actions actions = new Actions(driver);

 

WebElement source = driver.findElement(

    By.id("source")

);

 

WebElement target = driver.findElement(

    By.id("target")

);

 

actions.dragAndDrop(source, target).perform();


43. Execute JavaScript

The JavaScriptExecutor interface can execute JavaScript in the context of the current page.

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].click();",

    driver.findElement(By.id("button"))

);


44. Scroll Down the Page

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "window.scrollBy(0,500);"

);


45. Scroll to an Element

WebElement element = driver.findElement(

    By.id("footer")

);

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].scrollIntoView(true);",

    element

);


46. Upload a File

For a standard HTML file input, Selenium can use sendKeys() to provide the file path.

WebElement upload = driver.findElement(

    By.id("fileUpload")

);

 

upload.sendKeys(

    "C:\\Users\\Test\\Documents\\sample.pdf"

);


47. Count Rows in a Web Table

List<WebElement> rows = driver.findElements(

    By.xpath("//table[@id='users']//tbody/tr")

);

 

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


48. Count Columns in a Web Table

List<WebElement> columns = driver.findElements(

    By.xpath("//table[@id='users']//thead/tr/th")

);

 

System.out.println("Columns: " + columns.size());


49. Read Data from a Web Table

List<WebElement> rows = driver.findElements(

    By.xpath("//table[@id='users']//tbody/tr")

);

 

for (WebElement row : rows) {

    System.out.println(row.getText());

}


50. Find a Specific Row in a Table

WebElement row = driver.findElement(

    By.xpath(

        "//table[@id='users']//tr[td[normalize-space()='John']]"

    )

);

 

System.out.println(row.getText());


51. Click a Checkbox in a Specific Table Row

WebElement checkbox = driver.findElement(

    By.xpath(

        "//table[@id='users']//tr[td[normalize-space()='John']]//input[@type='checkbox']"

    )

);

 

if (!checkbox.isSelected()) {

    checkbox.click();

}


52. Find All Links on a Page

List<WebElement> links = driver.findElements(

    By.tagName("a")

);

 

for (WebElement link : links) {

    System.out.println(

        link.getText() + " : " +

        link.getAttribute("href")

    );

}


53. Verify Broken Links

A common practical exercise is to collect page links and verify their HTTP responses. This generally requires Java HTTP functionality or a suitable HTTP client in addition to Selenium.

List<WebElement> links = driver.findElements(

    By.tagName("a")

);

 

for (WebElement link : links) {

    String url = link.getAttribute("href");

 

    if (url != null && !url.isBlank()) {

        System.out.println("Checking: " + url);

    }

}

In a production framework, the collected URLs can be sent through an HTTP client and their response status can be validated.


54. Verify a Page URL

String currentUrl = driver.getCurrentUrl();

 

Assert.assertEquals(

    currentUrl,

    "https://example.com/dashboard"

);


55. Verify an Element Text

String actualMessage = driver.findElement(

    By.id("message")

).getText();

 

Assert.assertEquals(

    actualMessage,

    "Login successful"

);


56. Verify an Element Contains Text

String message = driver.findElement(

    By.id("message")

).getText();

 

Assert.assertTrue(

    message.contains("successful")

);


57. Handle Cookies

Selenium allows cookies to be added, retrieved, and deleted.

Cookie cookie = new Cookie(

    "testCookie",

    "testValue"

);

 

driver.manage().addCookie(cookie);

 

System.out.println(

    driver.manage().getCookieNamed("testCookie")

);


58. Delete Cookies

driver.manage().deleteAllCookies();


59. Handle Browser Navigation

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

 

driver.navigate().to("https://example.com/login");

 

driver.navigate().back();

 

driver.navigate().forward();

 

driver.navigate().refresh();


60. Maximize Browser Window

driver.manage().window().maximize();


61. Set Browser Window Size

driver.manage().window().setSize(

    new Dimension(1280, 720)

);


62. Verify Login with TestNG

TestNG provides assertions and test lifecycle annotations that can be combined with Selenium.

import org.testng.Assert;

import org.testng.annotations.Test;

 

@Test

public void loginTest() {

    driver.findElement(By.id("username"))

          .sendKeys("admin");

 

    driver.findElement(By.id("password"))

          .sendKeys("admin123");

 

    driver.findElement(By.id("loginButton"))

          .click();

 

    Assert.assertTrue(

        driver.getTitle().contains("Dashboard")

    );

}


63. Use DataProvider for Multiple Login Tests

Data Providers allow the same Selenium workflow to execute against multiple data sets.

@DataProvider(name = "loginData")

public Object[][] loginData() {

    return new Object[][] {

        {"admin", "admin123"},

        {"manager", "manager123"},

        {"employee", "employee123"}

    };

}

 

@Test(dataProvider = "loginData")

public void loginTest(

        String username,

        String password) {

 

    driver.findElement(By.id("username"))

          .sendKeys(username);

 

    driver.findElement(By.id("password"))

          .sendKeys(password);

 

    driver.findElement(By.id("loginButton"))

          .click();

}


64. Use BeforeMethod for Browser Setup

@BeforeMethod

public void setup() {

    driver = new ChromeDriver();

    driver.manage().window().maximize();

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

}


65. Use AfterMethod for Browser Cleanup

@AfterMethod

public void tearDown() {

    if (driver != null) {

        driver.quit();

    }

}


66. Practical Login Automation

A complete login test should normally contain setup, navigation, element interaction, validation, and cleanup.

public class LoginTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

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

    }

 

    @Test

    public void validLoginTest() {

 

        driver.findElement(By.id("username"))

              .sendKeys("admin");

 

        driver.findElement(By.id("password"))

              .sendKeys("admin123");

 

        driver.findElement(By.id("loginButton"))

              .click();

 

        WebDriverWait wait = new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

        wait.until(

            ExpectedConditions.urlContains("dashboard")

        );

 

        Assert.assertTrue(

            driver.getCurrentUrl().contains("dashboard")

        );

    }

 

    @AfterMethod

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}


67. Practical Search Automation

@Test

public void searchTest() {

 

    WebElement search = driver.findElement(

        By.id("search")

    );

 

    search.clear();

    search.sendKeys("Laptop");

    search.sendKeys(Keys.ENTER);

 

    WebDriverWait wait = new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

    );

 

    WebElement result = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("searchResults")

        )

    );

 

    Assert.assertTrue(

        result.isDisplayed()

    );

}


68. Practical Registration Form Automation

@Test

public void registrationTest() {

 

    driver.findElement(By.id("firstName"))

          .sendKeys("John");

 

    driver.findElement(By.id("lastName"))

          .sendKeys("Smith");

 

    driver.findElement(By.id("email"))

          .sendKeys("[email protected]");

 

    driver.findElement(By.id("mobile"))

          .sendKeys("9876543210");

 

    driver.findElement(By.id("terms"))

          .click();

 

    driver.findElement(By.id("register"))

          .click();

 

    Assert.assertTrue(

        driver.findElement(

            By.id("successMessage")

        ).isDisplayed()

    );

}


69. Practical E-Commerce Test

A common real-world Selenium scenario is to search for a product, open its details, add it to the cart, and verify the cart.

@Test

public void addProductToCart() {

 

    driver.findElement(By.id("search"))

          .sendKeys("Laptop");

 

    driver.findElement(By.id("searchButton"))

          .click();

 

    driver.findElement(

        By.xpath("//button[@data-product='Laptop']")

    ).click();

 

    WebDriverWait wait = new WebDriverWait(

        driver,

        Duration.ofSeconds(10)

    );

 

    WebElement cart = wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("cart")

        )

    );

 

    Assert.assertTrue(cart.isDisplayed());

}


70. Practical POM-Based Selenium Test

In a maintainable framework, page interaction logic should be separated into page classes while test classes coordinate scenarios and assertions.

public class LoginPage {

 

    private WebDriver driver;

 

    private By username =

        By.id("username");

 

    private By password =

        By.id("password");

 

    private By loginButton =

        By.id("loginButton");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String value) {

        driver.findElement(username)

              .sendKeys(value);

    }

 

    public void enterPassword(String value) {

        driver.findElement(password)

              .sendKeys(value);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton)

              .click();

    }

 

    public void login(

            String user,

            String pass) {

 

        enterUsername(user);

        enterPassword(pass);

        clickLogin();

    }

}

The test class can then use the page object:

@Test

public void loginTest() {

 

    LoginPage loginPage =

        new LoginPage(driver);

 

    loginPage.login(

        "admin",

        "admin123"

    );

 

    Assert.assertTrue(

        driver.getCurrentUrl()

              .contains("dashboard")

    );

}


71. Practical Question: How Would You Handle a Dynamic ID?

If an ID changes dynamically, avoid depending on the changing portion when another stable attribute or relationship is available.

driver.findElement(

    By.xpath(

        "//input[starts-with(@id,'user_')]"

    )

).sendKeys("admin");

CSS can also be used:

driver.findElement(

    By.cssSelector("input[id^='user_']")

).sendKeys("admin");


72. Practical Question: How Would You Handle an Element That Appears After Loading?

Use an explicit wait for the required condition instead of relying on an arbitrary sleep.

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(15)

);

 

WebElement element = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("dynamicButton")

    )

);

 

element.click();


73. Practical Question: How Would You Handle a Test That Fails Intermittently?

Intermittent failures should be investigated rather than simply hidden with retries. Common causes include synchronization problems, unstable locators, shared state, environment instability, stale elements, and test-order dependencies.

A practical debugging process is:

  1. Identify the exact failing step.
  2. Review screenshots and logs.
  3. Check browser and application timing.
  4. Verify locator stability.
  5. Replace fixed sleeps with appropriate waits.
  6. Check for stale elements.
  7. Verify test-data isolation.
  8. Run the test repeatedly to reproduce the problem.
  9. Fix the underlying cause.


74. Practical Question: How Would You Handle NoSuchElementException?

First verify that the locator is correct and that the element exists in the expected page context. Then check synchronization, iframe context, window context, and application state.

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement element = wait.until(

    ExpectedConditions.presenceOfElementLocated(

        By.id("username")

    )

);


75. Practical Question: How Would You Handle ElementClickInterceptedException?

This exception can occur when another element overlaps the target or when the page has not reached the expected interaction state.

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement button = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.id("submit")

    )

);

 

button.click();

The underlying page state should still be investigated if the problem continues.


76. Practical Question: How Would You Handle Stale Elements?

Locate the element again after the DOM changes rather than continuing to use an old WebElement reference.

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

WebElement button = wait.until(

    ExpectedConditions.refreshed(

        ExpectedConditions.elementToBeClickable(

            By.id("submit")

        )

    )

);

 

button.click();


77. Practical Question: How Would You Run Tests on Multiple Browsers?

Browser configuration can be combined with TestNG parameters or a driver factory.

@Parameters("browser")

@BeforeMethod

public void setup(String browser) {

 

    if (browser.equalsIgnoreCase("chrome")) {

        driver = new ChromeDriver();

    } else if (browser.equalsIgnoreCase("firefox")) {

        driver = new FirefoxDriver();

    } else if (browser.equalsIgnoreCase("edge")) {

        driver = new EdgeDriver();

    } else {

        throw new IllegalArgumentException(

            "Unsupported browser: " + browser

        );

    }

}


78. Practical Question: How Would You Run Tests in Parallel?

TestNG can configure parallel execution in testng.xml. Parallel execution requires thread-safe framework components and isolated browser sessions.

<suite name="CrossBrowserSuite" parallel="tests" thread-count="3">

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

 

    <test name="EdgeTest">

        <parameter name="browser" value="edge"/>

        <classes>

            <class name="tests.LoginTest"/>

        </classes>

    </test>

</suite>


79. Practical Question: How Would You Create a Reusable Driver Factory?

A Driver Factory centralizes browser creation so test classes do not need to contain repeated browser initialization logic.

public class DriverFactory {

 

    public static WebDriver createDriver(

            String browser) {

 

        if (browser.equalsIgnoreCase("chrome")) {

            return new ChromeDriver();

        }

 

        if (browser.equalsIgnoreCase("firefox")) {

            return new FirefoxDriver();

        }

 

        if (browser.equalsIgnoreCase("edge")) {

            return new EdgeDriver();

        }

 

        throw new IllegalArgumentException(

            "Unsupported browser: " + browser

        );

    }

}


80. Practical Question: How Would You Design a Selenium Framework?

A maintainable Selenium framework commonly separates tests, page objects, utilities, driver management, test data, configuration, and reporting.

src

|-- test

|   |-- java

|       |-- tests

|       |   |-- LoginTest.java

|       |   |-- SearchTest.java

|       |   |-- CheckoutTest.java

|       |

|       |-- pages

|       |   |-- LoginPage.java

|       |   |-- SearchPage.java

|       |   |-- CheckoutPage.java

|       |

|       |-- utilities

|       |   |-- DriverFactory.java

|       |   |-- ScreenshotUtil.java

|       |   |-- ConfigReader.java

|       |

|       |-- data

|       |   |-- LoginDataProvider.java

|       |

|       |-- listeners

|           |-- TestListener.java

|

|-- resources

    |-- config.properties

    |-- test-data


81. Practical Question: How Would You Read Configuration from a Properties File?

Properties properties = new Properties();

 

try (FileInputStream input =

         new FileInputStream("config.properties")) {

 

    properties.load(input);

}

 

String url = properties.getProperty("baseUrl");

 

driver.get(url);

This keeps environment-specific configuration separate from test code.


82. Practical Question: How Would You Capture a Screenshot for a Failed Test?

A TestNG listener can detect failures and call a reusable screenshot utility.

public class TestListener

        implements ITestListener {

 

    @Override

    public void onTestFailure(

            ITestResult result) {

 

        WebDriver driver =

            DriverManager.getDriver();

 

        if (driver != null) {

            ScreenshotUtil.capture(

                driver,

                result.getName()

            );

        }

    }

}


83. Practical Question: How Would You Generate Test Reports?

TestNG can produce execution results, while reporting libraries such as ExtentReports or Allure can provide richer reporting and visualization. TestNG is commonly integrated with Selenium frameworks for test execution, data-driven testing, listeners, and reporting workflows. :contentReference[oaicite:0]{index=0}

A typical reporting flow is:

Test Execution

      |

      v

TestNG

      |

      v

Listener

      |

      +------> Pass

      |

      +------> Fail

      |           |

      |           v

      |       Screenshot

      |

      v

Report Generator

      |

      v

HTML / Allure / Extent Report


84. Practical Question: How Would You Retry a Failed Test?

Retry mechanisms can be useful for carefully diagnosed transient failures, but they should not be used to hide genuine application or synchronization defects.

public class RetryAnalyzer

        implements IRetryAnalyzer {

 

    private int count = 0;

    private static final int maxRetry = 2;

 

    @Override

    public boolean retry(

            ITestResult result) {

 

        if (count < maxRetry) {

            count++;

            return true;

        }

 

        return false;

    }

}


85. Practical Question: How Would You Handle a Broken Locator?

Locator failures should be investigated by inspecting the current DOM and checking whether the locator depends on unstable attributes.

ProblemPossible Solution
Dynamic IDUse stable attributes, CSS, XPath relationships, or data attributes.
Element not loadedUse an explicit wait.
Element inside iframeSwitch to the appropriate frame.
Element in another windowSwitch to the correct window or tab.
DOM refreshedRe-locate the element.
Overlapping elementWait for the correct interaction state and investigate overlays.


86. Practical Question: How Would You Handle a Calendar?

Dynamic calendars usually require locating the calendar controls and selecting the required month, year, and day.

while (!driver.findElement(

        By.cssSelector(".month")

    ).getText().equals("December")) {

 

    driver.findElement(

        By.id("nextMonth")

    ).click();

}

 

driver.findElement(

    By.xpath("//button[normalize-space()='25']")

).click();

The exact implementation depends on the calendar's HTML structure.


87. Practical Question: How Would You Handle Auto-Suggest Search?

WebElement search = driver.findElement(

    By.id("search")

);

 

search.sendKeys("Selenium");

 

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

List<WebElement> suggestions =

    wait.until(

        ExpectedConditions.visibilityOfAllElementsLocatedBy(

            By.cssSelector(".suggestion")

        )

    );

 

for (WebElement suggestion : suggestions) {

    if (suggestion.getText().equals("Selenium WebDriver")) {

        suggestion.click();

        break;

    }

}


88. Practical Question: How Would You Handle a Web Table with Pagination?

For paginated tables, read the current page and then navigate to the next page until the required row is found or there are no more pages.

boolean found = false;

 

while (!found) {

 

    List<WebElement> rows = driver.findElements(

        By.cssSelector("table tbody tr")

    );

 

    for (WebElement row : rows) {

        if (row.getText().contains("John")) {

            found = true;

            System.out.println(row.getText());

            break;

        }

    }

 

    if (!found) {

        WebElement next = driver.findElement(

            By.id("nextPage")

        );

 

        if (!next.isEnabled()) {

            break;

        }

 

        next.click();

    }

}


89. Practical Question: How Would You Handle Multiple Tabs?

String originalWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("openNewTab")

).click();

 

for (String window :

        driver.getWindowHandles()) {

 

    if (!window.equals(originalWindow)) {

        driver.switchTo().window(window);

        break;

    }

}

 

System.out.println(

    "New tab title: " + driver.getTitle()

);

 

driver.close();

 

driver.switchTo().window(originalWindow);


90. Practical Question: How Would You Verify a File Download?

Selenium controls the browser interaction, while the downloaded file can be verified through Java file-system APIs.

Path downloadedFile =

    Paths.get(

        "C:\\Downloads\\report.pdf"

    );

 

if (Files.exists(downloadedFile)) {

    System.out.println(

        "File downloaded successfully"

    );

}


91. Practical Question: How Would You Handle Authentication Popups?

Modern applications may use web forms, browser-managed authentication, tokens, or other authentication mechanisms. The correct solution depends on how the application implements authentication.

For a basic HTTP-authentication scenario, a URL may sometimes be used in the form:

https://username:[email protected]

Credentials should not be exposed in source code or logs. Secure authentication mechanisms should be preferred for real projects.


92. Practical Question: How Would You Validate All Form Fields?

A practical form-validation test can iterate through required fields and verify their validation messages.

driver.findElement(

    By.id("submit")

).click();

 

List<WebElement> errors =

    driver.findElements(

        By.cssSelector(".validation-error")

    );

 

Assert.assertTrue(

    errors.size() > 0,

    "Expected validation errors were not displayed"

);


93. Practical Question: How Would You Test Logout?

driver.findElement(

    By.id("logout")

).click();

 

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

wait.until(

    ExpectedConditions.urlContains("login")

);

 

Assert.assertTrue(

    driver.getCurrentUrl().contains("login")

);


94. Practical Question: How Would You Verify That a User Cannot Access a Protected Page After Logout?

driver.findElement(

    By.id("logout")

).click();

 

driver.get(

    "https://example.com/dashboard"

);

 

WebDriverWait wait = new WebDriverWait(

    driver,

    Duration.ofSeconds(10)

);

 

wait.until(

    ExpectedConditions.urlContains("login")

);

 

Assert.assertTrue(

    driver.getCurrentUrl().contains("login")

);


95. Practical Question: How Would You Organize Test Data?

Test data can be managed using TestNG Data Providers, Excel, CSV, JSON, databases, properties files, or dedicated data classes depending on the project's requirements.

Test Data

    |

    +-- Login Data

    |

    +-- Search Data

    |

    +-- Product Data

    |

    +-- User Role Data

    |

    +-- Environment Data

    |

    v

Data Provider / Data Reader

    |

    v

Test Method


96. Practical Question: How Would You Create a Reusable Login Test?

The test should separate test data, page interactions, driver management, and assertions.

@DataProvider(name = "loginData")

public Object[][] loginData() {

    return new Object[][] {

        {"admin", "admin123"},

        {"manager", "manager123"},

        {"employee", "employee123"}

    };

}

 

@Test(dataProvider = "loginData")

public void loginTest(

        String username,

        String password) {

 

    LoginPage loginPage =

        new LoginPage(driver);

 

    loginPage.login(

        username,

        password

    );

 

    Assert.assertTrue(

        driver.getCurrentUrl()

              .contains("dashboard")

    );

}


97. Practical Selenium Scenario-Based Questions

The following scenarios are useful for hands-on practice and interview preparation. Selenium interviews commonly cover WebDriver, locators, synchronization, alerts, frames, windows, TestNG, POM, Grid, and real-world troubleshooting scenarios. :contentReference[oaicite:1]{index=1}

  1. Automate a login page with valid credentials.
  2. Automate a login page with invalid credentials.
  3. Verify an error message for empty login fields.
  4. Search for multiple products using a Data Provider.
  5. Select a product and add it to the cart.
  6. Verify the cart item count.
  7. Apply a discount code and validate the result.
  8. Automate a registration form.
  9. Validate required form fields.
  10. Handle a JavaScript alert.
  11. Handle a confirmation popup.
  12. Switch into an iframe.
  13. Handle nested iframes.
  14. Switch between browser tabs.
  15. Read data from a dynamic table.
  16. Find a row based on a specific cell value.
  17. Handle pagination in a table.
  18. Automate an auto-suggestion search box.
  19. Handle a dynamic dropdown.
  20. Select a date from a calendar.
  21. Upload a file.
  22. Verify a downloaded file.
  23. Capture a screenshot after a failure.
  24. Run tests on multiple browsers.
  25. Execute tests in parallel.
  26. Build a POM-based login framework.
  27. Read test data from Excel.
  28. Generate execution reports.
  29. Handle Selenium exceptions.
  30. Integrate Selenium tests with Maven and CI/CD.


98. Practical Coding Questions

Question 1: Write code to launch Chrome and open a website.

WebDriver driver = new ChromeDriver();

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

Question 2: Write code to locate an element by ID.

driver.findElement(

    By.id("username")

).sendKeys("admin");

Question 3: Write an XPath for a button with ID login.

//button[@id='login']

Question 4: Write an XPath using text.

//button[normalize-space()='Login']

Question 5: Write code to select India from a dropdown.

Select select = new Select(

    driver.findElement(By.id("country"))

);

 

select.selectByVisibleText("India");

Question 6: Write code to accept an alert.

driver.switchTo().alert().accept();

Question 7: Write code to switch into an iframe.

driver.switchTo().frame("frame1");

Question 8: Write code to return from an iframe.

driver.switchTo().defaultContent();

Question 9: Write code to get the current URL.

String url = driver.getCurrentUrl();

Question 10: Write code to get the page title.

String title = driver.getTitle();


99. Practical Debugging Checklist

  • Check whether the correct URL is loaded.
  • Verify the locator in the current DOM.
  • Check whether the element is inside an iframe.
  • Check whether the element is inside another browser window or tab.
  • Use an explicit wait for dynamic content.
  • Check for overlays or loading screens.
  • Check for stale element references.
  • Verify test data.
  • Check browser and driver compatibility.
  • Review screenshots and logs.
  • Check whether tests depend on execution order.
  • Verify that browser sessions are isolated during parallel execution.
  • Check whether the failure is application-related or automation-related.


100. Selenium Practical Project Flow

Requirement

    |

    v

Test Scenario

    |

    v

Test Case

    |

    v

Locator Identification

    |

    v

Page Object

    |

    v

TestNG Test

    |

    v

Test Data

    |

    v

Selenium WebDriver

    |

    v

Browser

    |

    v

Application

    |

    v

Assertion

    |

    v

Listener / Screenshot

    |

    v

Test Report

    |

    v

CI/CD Pipeline


101. Selenium Practical Interview Questions

1. How do you handle dynamic elements?

Use stable attributes, relative XPath or CSS selectors, and appropriate synchronization. Avoid depending on unstable dynamic identifiers when better attributes are available.

2. What is the difference between findElement() and findElements()?

findElement() returns the first matching element and throws an exception when no matching element is found. findElements() returns a list and returns an empty list when there are no matches.

3. How do you handle synchronization?

Use appropriate explicit waits for conditions such as visibility, presence, clickability, URL changes, or text changes.

4. How do you handle multiple windows?

Use window handles and switch to the required window using switchTo().window().

5. How do you handle frames?

Use switchTo().frame() and return to the main document using defaultContent().

6. How do you handle alerts?

Use driver.switchTo().alert(), followed by methods such as accept(), dismiss(), or sendKeys().

7. How do you perform mouse actions?

Use Selenium's Actions class for hover, double-click, right-click, drag-and-drop, and related interactions.

8. How do you capture screenshots?

Use TakesScreenshot and connect it with failure handling or TestNG listeners.

9. How do you implement data-driven testing?

TestNG Data Providers can supply multiple data sets to the same test method, while external sources such as Excel, CSV, JSON, or databases can be read through supporting utilities.

10. How do you make Selenium tests maintainable?

Use stable locators, explicit waits, Page Object Model, reusable utilities, isolated test data, centralized driver management, meaningful assertions, logging, screenshots, and reporting.


102. Common Mistakes in Selenium Practical Tests

  • Using Thread.sleep() everywhere instead of condition-based waits.
  • Using unstable XPath expressions.
  • Hard-coding environment-specific URLs throughout the framework.
  • Sharing WebDriver instances incorrectly between parallel tests.
  • Putting all Selenium code inside one large test class.
  • Mixing page interaction logic with test-data management.
  • Ignoring browser context such as frames and windows.
  • Not validating expected results.
  • Using retry logic to hide real failures.
  • Hard-coding sensitive credentials.
  • Not capturing useful logs and screenshots for failures.
  • Creating tests that depend on execution order.


103. Best Practices for Selenium Practical Automation

  • Use Page Object Model for reusable page interactions.
  • Prefer stable IDs or dedicated test attributes where available.
  • Use CSS selectors and XPath carefully for dynamic elements.
  • Use explicit waits for synchronization.
  • Keep test methods focused on business scenarios.
  • Keep reusable browser logic in utilities or driver factories.
  • Use Data Providers for repeated test data.
  • Separate test data from test implementation.
  • Use assertions to validate actual application behavior.
  • Capture screenshots for important failures.
  • Use listeners for centralized reporting and failure handling.
  • Keep browser sessions isolated during parallel execution.
  • Use Maven for dependency and build management.
  • Integrate automation with CI/CD where appropriate.
  • Keep credentials and secrets outside source-controlled test code.


104. Practical Project Structure

selenium-automation

|

|-- pom.xml

|

|-- src

|   |-- main

|   |   |-- java

|   |       |-- pages

|   |       |   |-- LoginPage.java

|   |       |   |-- SearchPage.java

|   |       |   |-- CartPage.java

|   |       |

|   |       |-- utilities

|   |           |-- DriverFactory.java

|   |           |-- ScreenshotUtil.java

|   |           |-- ConfigReader.java

|   |

|   |-- test

|       |-- java

|           |-- tests

|           |   |-- LoginTest.java

|           |   |-- SearchTest.java

|           |   |-- CartTest.java

|           |

|           |-- data

|           |   |-- LoginDataProvider.java

|           |

|           |-- listeners

|               |-- TestListener.java

|

|-- src

|   |-- test

|       |-- resources

|           |-- config.properties

|           |-- testng.xml

|

|-- reports

|

|-- screenshots


105. Complete Practical Selenium Test Example

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class LoginTest {

 

    private WebDriver driver;

    private WebDriverWait wait;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

 

        driver.manage().window().maximize();

 

        wait = new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

        driver.get(

            "https://example.com/login"

        );

    }

 

    @DataProvider(name = "loginData")

    public Object[][] loginData() {

        return new Object[][] {

            {"admin", "admin123"},

            {"manager", "manager123"}

        };

    }

 

    @Test(dataProvider = "loginData")

    public void loginTest(

            String username,

            String password) {

 

        wait.until(

            ExpectedConditions.visibilityOfElementLocated(

                By.id("username")

            )

        ).sendKeys(username);

 

        driver.findElement(

            By.id("password")

        ).sendKeys(password);

 

        wait.until(

            ExpectedConditions.elementToBeClickable(

                By.id("loginButton")

            )

        ).click();

 

        Assert.assertTrue(

            driver.getCurrentUrl()

                  .contains("dashboard")

        );

    }

 

    @AfterMethod

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}


106. Selenium Practical Learning Roadmap

  1. Learn Selenium WebDriver basics.
  2. Practice browser navigation.
  3. Practice all major locator strategies.
  4. Automate text fields and buttons.
  5. Automate checkboxes and radio buttons.
  6. Practice dropdown handling.
  7. Practice explicit waits.
  8. Practice alerts and popups.
  9. Practice frames and nested frames.
  10. Practice multiple windows and tabs.
  11. Practice mouse and keyboard actions.
  12. Practice JavaScriptExecutor.
  13. Practice screenshots.
  14. Practice tables and pagination.
  15. Practice file upload and download validation.
  16. Learn TestNG annotations and assertions.
  17. Learn Data Providers.
  18. Learn Page Object Model.
  19. Create reusable page classes.
  20. Create reusable driver and utility classes.
  21. Implement listeners and reporting.
  22. Run tests on multiple browsers.
  23. Implement parallel execution safely.
  24. Integrate Maven.
  25. Integrate CI/CD.
  26. Build a complete Selenium automation framework.


107. Quick Reference Table

Practical AreaImportant Selenium Concept
BrowserWebDriver, navigation, window management
LocatorsID, Name, Class, CSS, XPath, Tag Name
FormssendKeys(), click(), clear()
DropdownSelect class
AlertsswitchTo().alert()
FramesswitchTo().frame()
WindowsgetWindowHandle(), getWindowHandles()
WaitsWebDriverWait and ExpectedConditions
MouseActions class
JavaScriptJavascriptExecutor
ScreenshotTakesScreenshot
TablesfindElements(), XPath/CSS
TestingTestNG, assertions, DataProvider
FrameworkPOM, Driver Factory, Utilities
ReportingTestNG reports, listeners, reporting tools
CI/CDMaven, Jenkins and pipeline execution


108. Summary

Selenium practical questions help learners develop the ability to solve real automation problems rather than only memorizing Selenium definitions. A strong Selenium tester should be able to automate complete user workflows, identify elements reliably, synchronize tests with application behavior, handle browser contexts, validate expected results, and troubleshoot failures.

Important practical areas include locators, browser management, forms, dropdowns, alerts, frames, windows, waits, dynamic elements, mouse and keyboard actions, JavaScript execution, screenshots, tables, file handling, TestNG, Data Providers, assertions, Page Object Model, reporting, parallel execution, and CI/CD.

Modern Selenium interview and framework preparation commonly combines WebDriver with Java, TestNG, POM, data-driven testing, reporting, Maven, CI/CD, and framework design concepts. :contentReference[oaicite:2]{index=2}

The most effective practice approach is to build complete scenarios such as login, registration, search, e-commerce checkout, role-based access, and regression workflows while keeping the automation code reusable and maintainable.


109. Final Practical Checklist

  • Can you launch and close a browser?
  • Can you use ID, CSS, and XPath locators?
  • Can you automate a login workflow?
  • Can you handle dynamic elements?
  • Can you use explicit waits?
  • Can you handle alerts?
  • Can you switch between frames?
  • Can you switch between browser tabs?
  • Can you automate dropdowns?
  • Can you handle checkboxes and radio buttons?
  • Can you perform mouse and keyboard actions?
  • Can you execute JavaScript?
  • Can you capture screenshots?
  • Can you automate web tables?
  • Can you handle file upload?
  • Can you validate downloaded files?
  • Can you write TestNG tests?
  • Can you use assertions?
  • Can you create a Data Provider?
  • Can you implement Page Object Model?
  • Can you create reusable page classes?
  • Can you handle Selenium exceptions?
  • Can you run tests on multiple browsers?
  • Can you execute tests safely in parallel?
  • Can you generate and analyze test reports?
  • Can you integrate Selenium with Maven and CI/CD?


110. Course Resources

Learn more about Selenium automation, TestNG, Page Object Model, practical automation, and related testing concepts:

Final Takeaway: Selenium practical skills are developed by repeatedly solving real browser-automation scenarios. Focus on writing reliable locators, using proper synchronization, separating page logic from test logic, validating results with assertions, handling failures with useful evidence, and building reusable automation components.

whatsapp