VIDHAIX / TESTING & QA / INTERVIEW PREP

Top 43 Selenium Interview Questions & Answers (2026)

Selenium 4 waits, locators, POM, Grid, CI and flakiness, with Java and Python answers and real scenario rounds.

43 questions with answersUpdated 22 October 2026Reviewed by VidhaiX trainers

This page is for manual testers moving into automation, freshers with a Selenium course on their resume, and automation engineers with a few years of Java and TestNG who are preparing for a switch. Selenium is still the most common automation stack in Indian service companies and many enterprise product teams, so it shows up in almost every QA interview, even at companies that have started adopting Playwright.

In 2026, interviewers rarely stop at "what is an XPath". They probe Selenium 4 specifics such as Selenium Manager and the W3C protocol, why your waits are flaky, how you keep WebDriver thread-safe in parallel runs, how Grid 4 is wired, and how you debug a suite that only fails in CI. The questions are grouped into freshers, intermediate, experienced (3+ years) and scenario rounds, compiled by VidhaiX trainers from the mock interviews they run. Examples are mostly Java with TestNG, with Python where it helps.

How to Prepare for a Selenium Interview

  • Build a small framework from scratch in Java with TestNG: a driver factory, three or four page objects, a DataProvider-driven test and a failure screenshot listener. Be ready to walk through every file.
  • Practise explicit waits until you can explain each ExpectedConditions method you use, and be able to say clearly why mixing implicit and explicit waits causes unpredictable timeouts.
  • Write ten locators for a real site such as an e-commerce checkout using CSS and relative XPath, avoiding absolute paths and generated IDs. Interviewers often hand you a page and ask for locators live.
  • Run your suite in parallel with ThreadLocal drivers, then run it against a Selenium Grid 4 started with Docker Compose. Note what broke and how you fixed it; that story is interview gold.
  • Wire the suite into a CI pipeline (GitHub Actions or Jenkins) running headless Chrome, publishing an Allure or Extent report and screenshots as build artifacts.
  • Keep a written log of two or three flaky tests you diagnosed: the symptom, the root cause, and the fix. Scenario rounds are judged on this kind of concrete experience.
  • Learn the basics of Playwright alongside Selenium. You will be asked to compare them, and an honest, balanced comparison signals maturity more than loyalty to either tool.

Selenium Interview Questions for Freshers

12 questions

Q1.What is Selenium, and what are its main components today?

Selenium is an open-source project for automating browsers. Its components are Selenium WebDriver (language bindings for Java, Python, C#, JavaScript and Ruby that drive real browsers), Selenium Grid (runs tests remotely and in parallel across machines and browsers), and Selenium IDE (a record-and-playback browser extension for quick scripts).

A strong answer also says Selenium is a browser automation library, not a test framework. Assertions, reporting and test organisation come from TestNG, JUnit or pytest. Mentioning Selenium RC as current is a red flag; it was removed long ago.

Q2.What changed in Selenium 4 compared to Selenium 3?

Selenium 4 speaks the W3C WebDriver protocol natively, so the old JSON Wire Protocol translation layer is gone and behaviour is more consistent across browsers. It added relative locators, element-level screenshots, newWindow() for tabs and windows, access to Chrome DevTools Protocol and the newer WebDriver BiDi, a rewritten Grid 4 with Docker support, and Selenium Manager for automatic driver setup.

Interviewers also like hearing that Duration replaced the old long timeouts in waits, and that DesiredCapabilities gave way to browser Options classes.

Q3.What is Selenium Manager, and do you still need WebDriverManager or manual driver downloads?

Selenium Manager is a tool bundled with the Selenium bindings since 4.6. When you create a driver without a driver path, it detects your browser version, downloads the matching driver (and, if needed, a browser such as Chrome for Testing), and caches it. For most projects you no longer need WebDriverManager or System.setProperty("webdriver.chrome.driver", ...).

A good answer adds the caveat: in locked-down corporate networks you may still configure a proxy, a mirror, or pre-installed drivers, because Selenium Manager needs internet access by default.

java
ChromeOptions options = new ChromeOptions();
options.setBrowserVersion("stable");
// No driver path: Selenium Manager resolves chromedriver automatically
WebDriver driver = new ChromeDriver(options);
driver.get("https://example.test");

Q4.Which locator strategies does Selenium support, and how do you decide which one to use?

Selenium supports id, name, className, tagName, linkText, partialLinkText, cssSelector and xpath, plus relative locators in Selenium 4. My order of preference is a stable dedicated attribute such as data-testid, then a unique id or name, then a short CSS selector, and XPath only when I need text matching or to walk up the DOM.

A weak answer lists the eight types. Interviewers want reasoning: locators should be unique, readable, and resilient to layout changes, and the best fix is often asking developers to add test IDs.

Q5.What is the difference between findElement and findElements?

findElement returns the first matching WebElement and throws NoSuchElementException if nothing matches after any implicit wait. findElements returns a List<WebElement> and returns an empty list instead of throwing when nothing matches.

That difference makes findElements(...).isEmpty() the idiomatic way to assert that something is absent, or to branch on an optional banner. The trap is that with an implicit wait set, findElements waits the full timeout before returning empty, which quietly slows down negative checks.

Q6.What is the difference between an implicit wait and an explicit wait?

An implicit wait is a global setting on the driver: every findElement call polls the DOM for up to that duration before failing. It only covers element presence. An explicit wait, WebDriverWait, waits for a specific condition on a specific element, such as visible, clickable, text present, or URL changed, and only where you call it.

Explicit waits are preferred because they express intent and handle conditions beyond presence. Most teams set implicit wait to zero and use explicit waits everywhere.

java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement save = wait.until(ExpectedConditions.elementToBeClickable(By.id("save")));
save.click();
wait.until(ExpectedConditions.textToBe(By.id("toast"), "Saved"));

Q7.What is the difference between driver.close() and driver.quit()?

close() closes the current window or tab that the driver is focused on. If it was the last window, the browser may exit, but the driver session can be left in a confusing state. quit() ends the whole WebDriver session, closes every window, and shuts down the driver process.

In test teardown you should always call quit(), usually in an @AfterMethod with alwaysRun = true. Forgetting it is a classic cause of leaked browser processes and exhausted Grid slots in CI.

Q8.How do you handle a dropdown in Selenium?

For a native HTML <select> element, wrap it in the Select class and use selectByVisibleText, selectByValue or selectByIndex, and read the choice with getFirstSelectedOption(). Visible text is most readable, value is most stable when labels are translated.

Most modern UIs use custom dropdowns built from div and li elements, where Select throws UnexpectedTagNameException. There you click the trigger, wait for the options list to be visible, and click the option by text. Interviewers often check whether you know this distinction.

Q9.How do you handle JavaScript alerts, confirms and prompts?

Switch to the alert with driver.switchTo().alert(), or better, wait for it with ExpectedConditions.alertIsPresent(). Then call accept(), dismiss(), getText(), or sendKeys() for a prompt. Until you handle it, other commands throw UnhandledAlertException.

A good answer separates native browser dialogs from HTML modal popups, which are ordinary DOM elements you locate normally. It can also mention the unhandledPromptBehavior capability, which controls whether unexpected alerts are auto-dismissed or cause an error.

Q10.What are relative locators in Selenium 4, and when are they useful?

Relative locators find an element by its visual position relative to another element, using above, below, toLeftOf, toRightOf and near. Selenium computes positions with getBoundingClientRect, so they reflect rendered layout rather than DOM structure.

They help when a field has no good attributes but sits next to a stable label. The honest caveat is that they depend on layout, so responsive breakpoints or a redesign can break them. I treat them as a fallback, not a default strategy.

java
import static org.openqa.selenium.support.locators.RelativeLocator.with;

WebElement emailLabel = driver.findElement(By.xpath("//label[text()='Email']"));
WebElement emailInput = driver.findElement(with(By.tagName("input")).below(emailLabel));
emailInput.sendKeys("qa@example.test");

Q11.How do you take a screenshot in Selenium, and can you capture a single element?

Cast the driver to TakesScreenshot and call getScreenshotAs with OutputType.FILE, BYTES or BASE64. Since Selenium 4, WebElement also implements screenshots, so you can capture just a chart or an error banner.

In a framework you rarely call this inside tests. You take screenshots automatically on failure from a TestNG listener or JUnit extension and attach them to the report. Note that standard screenshots capture the viewport; full-page capture is available in Firefox through getFullPageScreenshotAs.

java
File page = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(page.toPath(), Path.of("target/screens/checkout.png"),
    StandardCopyOption.REPLACE_EXISTING);

File chart = driver.findElement(By.id("sales-chart")).getScreenshotAs(OutputType.FILE);

Q12.What is the difference between driver.get() and driver.navigate().to()?

Both load a URL and wait for the page load strategy to be satisfied, which by default means document.readyState is complete. navigate() also exposes back(), forward() and refresh(), so it is useful when the test exercises browser history.

A sharper answer adds that "page loaded" does not mean "app ready". Single-page apps keep fetching data after load, so you still need an explicit wait for the element or state you care about. You can also tune pageLoadStrategy to eager or none when appropriate.

Selenium Intermediate Interview Questions

12 questions

Q13.Why is it a bad idea to mix implicit and explicit waits?

The Selenium documentation explicitly warns against it because the timeouts interact unpredictably. Implicit waits are applied inside the driver or remote end, while explicit waits poll from the client. An explicit wait for invisibility can end up waiting the implicit timeout on every poll, so a 10 second implicit plus 15 second explicit can produce waits far longer than either.

The standard practice is implicit wait set to zero and explicit waits wrapped in helper methods. Interviewers want to hear that you have seen these mysterious long timeouts and know their cause.

Q14.What is FluentWait, and when would you use it instead of WebDriverWait?

FluentWait lets you configure the timeout, polling interval, which exceptions to ignore, and a custom message. WebDriverWait is actually a subclass of FluentWait with sensible defaults, ignoring NoSuchElementException.

I reach for an explicitly configured FluentWait when polling something slow, such as a background job status that updates every few seconds, or when I need to ignore StaleElementReferenceException while a list re-renders. The condition is just a lambda returning a non-null value or true when done.

java
Wait<WebDriver> wait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(60))
    .pollingEvery(Duration.ofSeconds(2))
    .ignoring(NoSuchElementException.class)
    .ignoring(StaleElementReferenceException.class)
    .withMessage("Report job did not complete");

wait.until(d -> d.findElement(By.id("job-status")).getText().equals("COMPLETED"));

Q15.What causes StaleElementReferenceException, and how do you fix it properly?

It means the WebElement reference you hold points to a DOM node that no longer exists, because the page re-rendered, a framework like React replaced the node, or you navigated. The element might look identical but it is a new node.

The proper fix is to locate elements late, close to when you use them, and to keep By locators in page objects instead of caching WebElement fields. Then wait for the re-render to finish. Blindly wrapping clicks in retry loops hides real bugs and is what interviewers hope you will not suggest first.

Q16.Explain the Page Object Model. Is PageFactory still a good choice?

POM puts each page or component behind a class that exposes user-level actions, such as loginAs, and hides locators. Tests read like business steps, and a UI change is fixed in one place. Methods return the next page object for fluent navigation, and assertions stay in tests.

PageFactory with @FindBy still works, but its lazy proxies cache elements in ways that cause staleness, and the Selenium team discourages it. Most current frameworks prefer plain By fields with explicit waits, or component objects for repeated widgets like tables and modals.

java
public class LoginPage {
    private final WebDriver driver;
    private final By email = By.id("email");
    private final By password = By.id("password");
    private final By submit = By.cssSelector("button[type='submit']");

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

    public DashboardPage loginAs(String user, String pass) {
        driver.findElement(email).sendKeys(user);
        driver.findElement(password).sendKeys(pass);
        driver.findElement(submit).click();
        return new DashboardPage(driver);
    }
}

Q17.How do you work with iframes and multiple windows or tabs?

For frames, use switchTo().frame() by name, id, index or WebElement (or wait with frameToBeAvailableAndSwitchToIt), then return with defaultContent() or parentFrame(). Elements inside a frame are invisible to the driver until you switch.

For windows, store the original handle, trigger the new window, wait until the handle count changes, then switch to the handle that is not the original. Selenium 4 also offers switchTo().newWindow(WindowType.TAB). Forgetting to switch back is the usual source of confusing failures.

java
driver.switchTo().frame("payment-frame");
driver.findElement(By.id("card-number")).sendKeys("4111111111111111");
driver.switchTo().defaultContent();

String original = driver.getWindowHandle();
driver.findElement(By.linkText("View invoice")).click();
new WebDriverWait(driver, Duration.ofSeconds(5))
    .until(ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(original)) driver.switchTo().window(handle);
}

Q18.When do you use JavascriptExecutor, and why can overusing it be a problem?

JavascriptExecutor runs scripts in the page via executeScript or executeAsyncScript. Legitimate uses are scrolling an element into view, reading values not exposed by WebDriver, setting up state such as local storage, or reading performance timings.

The trap is using a JS click() to "fix" an element that is not clickable. That bypasses the visibility and overlay checks a real user would hit, so the test can pass while the actual button is covered by a modal. Interviewers want to hear that you fix the root cause first.

Q19.How do you perform hover, drag-and-drop and keyboard shortcuts with the Actions class?

The Actions class builds a sequence of low-level W3C input actions, then sends them with perform(). Common methods are moveToElement for hover menus, dragAndDrop or clickAndHold plus moveToElement plus release, doubleClick, contextClick, and keyDown/keyUp for modifier keys.

Two points stand out in interviews: forgetting perform() means nothing happens, and HTML5 drag-and-drop in some apps does not respond to synthetic mouse moves, so you may need a smaller step-by-step move sequence or to test the logic another way.

java
new Actions(driver)
    .moveToElement(driver.findElement(By.id("account-menu")))
    .pause(Duration.ofMillis(300))
    .click(driver.findElement(By.linkText("Settings")))
    .perform();

new Actions(driver)
    .keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL)
    .perform();

Q20.How do you build data-driven tests in TestNG?

Use a @DataProvider method that returns Object[][] or an Iterator<Object[]>, and point the test at it with dataProvider. Data can come from a CSV, JSON, Excel via Apache POI, or a database, but keep the reading code outside the test class.

Strong candidates mention keeping test data independent per row so rows can run with parallel = true, avoiding shared accounts that collide, and generating unique data such as emails at runtime rather than reusing fixed records that a previous run already modified.

java
@DataProvider(name = "logins", parallel = true)
public Object[][] logins() {
    return new Object[][] {
        {"admin@example.test", "Admin@123", true},
        {"admin@example.test", "wrong-pass", false},
    };
}

@Test(dataProvider = "logins")
public void login(String email, String password, boolean shouldPass) {
    boolean ok = new LoginPage(DriverFactory.get()).tryLogin(email, password);
    Assert.assertEquals(ok, shouldPass);
}

Q21.TestNG or JUnit 5 for a Selenium framework: how do you choose?

TestNG has long been the default in Indian QA teams because of testng.xml suites, groups, dependsOnMethods, DataProvider and built-in parallel modes. JUnit 5 (Jupiter) caught up with parameterized tests, tags, extensions and configurable parallel execution, and it is more common in developer-owned Java projects.

A mature answer says the choice matters less than consistency with the team and the CI tooling. It also warns that heavy use of dependsOnMethods creates order-dependent tests that are hard to parallelise and debug.

Q22.How do you write a robust XPath, and why should you avoid absolute XPath?

Absolute XPath such as /html/body/div[2]/div/form/input[3] breaks with any layout change. Robust relative XPath anchors on meaningful attributes or text, for example //button[normalize-space()='Place order'], and uses axes like ancestor:: or following-sibling:: to reach elements near a stable anchor, such as a table row containing a specific order ID.

Interviewers also check that you know CSS cannot match by text or walk up the tree, which is exactly where XPath earns its place, and that index-based selectors like [3] are fragile.

Q23.How do you handle file uploads and downloads in Selenium?

For upload, call sendKeys with an absolute file path on the input[type=file] element, even if it is visually hidden behind a styled button. Never automate the OS file dialog. On a remote Grid, set a LocalFileDetector on the RemoteWebDriver so the file is shipped to the node.

For downloads, set the browser download directory through options and wait for the file to appear. On Grid 4 you can enable managed downloads. Often the better test is to call the download URL with an HTTP client and verify the content directly.

Q24.How does a typical Selenium test look in Python with pytest?

The ideas are identical to Java: a fixture creates and quits the driver, tests use By locators and WebDriverWait with expected_conditions, and page objects wrap interactions. Python bindings also use Selenium Manager, so webdriver.Chrome() works without a driver path.

Interviewers like seeing the fixture with yield so teardown always runs, and pytest-xdist for parallel runs. Mentioning conftest.py for shared fixtures and a hook that saves a screenshot on failure shows real project experience.

python
import pytest
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

@pytest.fixture
def driver():
    d = webdriver.Chrome()
    yield d
    d.quit()

def test_login(driver):
    driver.get("https://example.test/login")
    driver.find_element(By.ID, "email").send_keys("qa@example.test")
    driver.find_element(By.ID, "password").send_keys("secret")
    driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
    WebDriverWait(driver, 10).until(EC.url_contains("/dashboard"))

Selenium Interview Questions for Experienced (3+ Years)

11 questions

Q25.Walk me through what happens when you call driver.findElement(...).click() in Selenium 4.

The language binding serialises the command into a W3C WebDriver HTTP request, for example a POST to find the element and another to click it, sent to the driver executable such as chromedriver, or to Grid which routes it to a node. The driver translates it into browser-internal automation calls, performs the actionability checks the spec defines, such as scrolling into view and checking the click target is not obscured, then returns a JSON response.

Strong candidates point out each command is a network round trip, which is why chatty tests are slow on remote Grids.

Q26.Explain the Selenium Grid 4 architecture.

Grid 4 is split into components: the Router (entry point that receives requests), the Distributor (matches new session requests to node slots by capabilities), the Session Map (session ID to node), the New Session Queue, the Event Bus (internal messaging), and Nodes that run browsers. Standalone runs everything in one process, Hub and Node splits it in two, and Distributed mode runs each component separately for scale.

Experienced answers mention the Grid UI and GraphQL endpoint for monitoring, session timeouts, and that Grid 4 integrates well with Docker and Kubernetes.

Q27.How would you run Selenium Grid with Docker for a team?

Use the official selenium/hub and selenium/node-* images with Docker Compose, pointing nodes at the hub event bus on ports 4442 and 4443, and tests at the hub on 4444 through RemoteWebDriver. Set shm_size to around 2 GB to avoid Chrome crashes, and tune max sessions per node to CPU.

For bigger teams, the docker-selenium project provides Helm charts for Kubernetes with autoscaling via KEDA. Video recording sidecars help debug failures. Pin image versions in CI so browser upgrades are deliberate, not surprises.

yaml
services:
  selenium-hub:
    image: selenium/hub:latest
    ports: ["4442:4442", "4443:4443", "4444:4444"]
  chrome:
    image: selenium/node-chrome:latest
    shm_size: 2gb
    depends_on: [selenium-hub]
    environment:
      - SE_EVENT_BUS_HOST=selenium-hub
      - SE_EVENT_BUS_PUBLISH_PORT=4442
      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
      - SE_NODE_MAX_SESSIONS=2

Q28.How do you make WebDriver thread-safe for parallel execution?

A WebDriver instance is not thread-safe, so each test thread needs its own. The common pattern is a driver factory holding a ThreadLocal<WebDriver>, created in @BeforeMethod and quit and removed in @AfterMethod. Page objects receive the driver through their constructor instead of reading a static field.

Experienced candidates add the other half: tests must not share data, accounts or static state, otherwise parallel runs fail randomly even with perfect driver isolation. Calling remove() matters because thread pools reuse threads.

java
public final class DriverFactory {
    private static final ThreadLocal<WebDriver> DRIVER = new ThreadLocal<>();

    public static void start() {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless=new");
        DRIVER.set(new ChromeDriver(options));
    }

    public static WebDriver get() { return DRIVER.get(); }

    public static void quit() {
        WebDriver driver = DRIVER.get();
        if (driver != null) { driver.quit(); DRIVER.remove(); }
    }
}

Q29.What is the difference between CDP and WebDriver BiDi in Selenium 4, and what would you use them for?

The Chrome DevTools Protocol gives Selenium low-level access to Chromium browsers: network interception, console logs, geolocation and throttling. It is Chromium-only and its versions are tied to the browser, which is why CDP-based code can break on upgrades. WebDriver BiDi is the W3C standard bidirectional protocol designed to provide similar capabilities across browsers.

Selenium is steadily moving its high-level features, like log listeners and network interception, to BiDi. Practical uses are capturing console errors, mocking or blocking third-party calls, and adding auth headers.

Q30.How would you structure a Selenium framework for a team of 10 automation engineers?

Layer it: configuration (environment URLs, browser, timeouts from properties or env vars), a driver factory supporting local and Grid, page and component objects, API helpers for test data setup, tests grouped by feature and tagged as smoke or regression, and reporting via listeners. Keep waits and common actions in a small base layer instead of a giant utility class.

The judgment interviewers look for is restraint: avoid over-abstracted keyword-driven layers nobody can debug, enforce code review on tests, and keep test code to the same standards as product code.

Q31.How do you set up reporting and failure evidence for a Selenium suite?

Use Allure or ExtentReports, hooked in through a TestNG ITestListener or JUnit 5 extension. On failure, attach a screenshot, page source, current URL, and browser console logs. On Grid, recorded video is invaluable for timing issues.

A senior answer focuses on making failures diagnosable without rerunning: clear step logging, test data identifiers in the report, and trend history to separate new failures from known flaky ones. Reports should be published as CI artifacts that anyone on the team can open.

java
public class FailureEvidenceListener implements ITestListener {
    @Override
    public void onTestFailure(ITestResult result) {
        WebDriver driver = DriverFactory.get();
        if (driver == null) return;
        byte[] png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
        Allure.addAttachment(result.getName(), "image/png",
            new ByteArrayInputStream(png), "png");
        Allure.addAttachment("url", driver.getCurrentUrl());
    }
}

Q32.How do you run Selenium tests in a CI pipeline?

Run browsers headless (--headless=new for Chrome) or against a Grid service container, trigger a fast smoke suite on every pull request and the full regression nightly or before release, and pass environment URLs and credentials through CI secrets. Use Maven or Gradle with TestNG groups or JUnit tags to select suites, and shard across parallel jobs when the suite grows.

Mature answers mention fixed window sizes so layouts match local runs, publishing reports as artifacts, and failing the build on real failures without silently auto-retrying everything.

Q33.Compare Selenium and Playwright honestly. Where does each one win?

Selenium wins on language reach (strong Java and C# ecosystems), the W3C standard, real branded browsers including Safari via safaridriver, a huge talent pool, and many existing enterprise frameworks and cloud grids. Playwright wins on developer experience: auto-waiting with actionability checks, browser contexts for fast isolation, built-in network mocking, a trace viewer, and a test runner with parallelism and retries out of the box.

The honest conclusion is that a well-engineered Selenium suite can be reliable, but Playwright makes reliability the default rather than something you build.

Q34.When does migrating from Selenium to Playwright make sense, and when does it not?

It makes sense when flakiness and maintenance cost are high, the team is comfortable with TypeScript or Playwright for Java, the app is a modern SPA, and you want built-in tracing and API testing. It makes less sense when a stable Selenium suite already delivers value, you depend on Grid vendors or real-device setups tied to WebDriver, or the team has no time to learn.

A good plan migrates incrementally: new tests in Playwright, high-value flaky Selenium tests ported first, and both suites running in CI until coverage matches.

Q35.How do you measure and reduce flakiness across a large Selenium suite?

First measure it: track per-test pass rates across runs, or rerun suites multiple times on the same build, and flag tests that pass and fail on identical code. Quarantine known flaky tests into a separate job so they do not block merges, with an owner and deadline for each.

Then fix root causes, which are usually missing or wrong waits, shared test data, order dependence, environment instability, or animations. Blanket retries hide the signal, so keep at most one retry and report retried passes as flaky rather than green.

Selenium Scenario-Based Interview Questions

8 questions

Q36.Your Selenium suite passes locally but fails randomly in CI. How do you investigate?

I first compare environments: CI usually runs headless with a smaller default window, less CPU, and parallel threads, so layout, timing and shared data all differ. I reproduce locally with the same window size, headless mode and thread count, then read the failure evidence: screenshots, console logs and Grid video.

Typical root causes are hard-coded sleeps that are too short on slow agents, elements hidden at smaller viewports, tests sharing a user account in parallel, and /dev/shm crashes in Docker. I fix each cause rather than adding retries.

Q37.A click fails with ElementClickInterceptedException on a button that is clearly visible. What do you do?

The exception tells you another element would receive the click, and its message names that element. Usually it is a loading overlay, a cookie banner, a sticky header covering the scrolled-into-view button, or a toast. I wait for the overlay to become invisible, dismiss the banner in setup, or scroll the element to the centre before clicking.

What I avoid is switching to a JavaScript click as the first fix, because a real user would also be blocked, and that might be a genuine bug worth reporting.

Q38.The application uses dynamic IDs and Shadow DOM web components. How do you locate elements?

For dynamic IDs like input-48291, anchor on stable attributes, labels, ARIA attributes or partial matches such as [id^='input-'] only if unique, and ideally ask developers for data-testid attributes. For Shadow DOM, Selenium 4 provides getShadowRoot() on the host element, and you search inside with CSS selectors.

Note that XPath does not work inside a shadow root, and nested components require chaining shadow roots, so wrapping this in a component object keeps tests readable.

java
WebElement host = driver.findElement(By.cssSelector("app-date-picker"));
SearchContext shadow = host.getShadowRoot();
shadow.findElement(By.cssSelector("input.date-input")).sendKeys("2026-10-22");

Q39.Your regression suite takes three hours and the team wants it under 30 minutes. What is your plan?

First profile it: which tests are slowest, how much time goes into login and data setup, and how many Thread.sleep calls exist. Then attack in order: replace sleeps with explicit waits, create test data and log in through APIs instead of the UI, delete or merge redundant UI tests that are better covered at API or unit level, and run in parallel on Grid with sharded CI jobs.

I would also split a fast smoke suite for pull requests from the full regression, so developers get feedback in minutes.

Q40.Every test logs in through the UI and it is slow and flaky. How would you change that?

Keep one dedicated test that covers the login UI properly. For all other tests, obtain a session through the API or a test-only auth endpoint, then inject the session cookie with driver.manage().addCookie() after opening any page on the domain, and navigate to the target page directly.

If the app uses tokens in local storage, set them via JavascriptExecutor instead. This typically removes several seconds and a common flakiness source from every test. Check with the security team that test-only shortcuts are never enabled in production.

Q41.Your manager wants all 800 Selenium tests migrated to Playwright within one quarter. How do you respond?

I would agree with the goal but challenge the plan. A line-by-line port carries old problems forward. I would first triage: retire tests that duplicate API coverage, port the most valuable and flakiest flows first, and write all new tests in Playwright. Both suites run in CI meanwhile, and Selenium tests are deleted only when their Playwright replacement has run green for a while.

I would give the manager a measurable target, such as critical journeys migrated and flaky rate reduced, rather than a raw test count.

Q42.Overnight, half the suite started failing after a Chrome update. What do you do?

Check whether the failures share an error such as a session-not-created version mismatch, a CDP-specific API breaking, or a changed default behaviour. With Selenium Manager, driver mismatches are rarer, but outdated Selenium bindings, CDP version dependencies, or a cached driver on CI agents can still bite.

The short-term fix is pinning the browser version through options or Docker image tags to unblock the pipeline. The long-term fix is upgrading Selenium regularly, preferring BiDi over raw CDP, and making browser upgrades a deliberate, tested change.

Q43.The login flow has a CAPTCHA and an OTP. How do you automate tests around it?

You should not try to defeat a CAPTCHA; it exists to block bots. In test environments, ask the team for a configuration that disables it or uses a test key that always passes. For OTP, use a test-only fixed OTP for designated accounts, fetch the code from a test SMS or email inbox API, or generate TOTP codes from the shared test secret.

Interviewers want to see that you solve this with the development team through testability hooks, not with fragile image recognition or manual steps in a supposedly automated suite.

From answers to offers

Prepare for Selenium interviews with practicing engineers

This course builds the skills these questions test: core Java, Selenium 4 and WebDriver, stable locators and waits, TestNG, a Page Object framework, Selenium Grid 4 and Jenkins, plus AI-assisted test design and debugging, with a hands-on lab in every module and an end-to-end capstone.