Autocoder

Selenium Interview Questions and Answers

Last updated 2026-11-19

Selenium interviews are practical. You are expected to choose a locator, explain why a test is flaky, write a wait correctly and structure a framework that other people can maintain. This page has 16 worked questions with Java and Python code for Selenium 4, covering locators, explicit waits, the Page Object Model, windows and frames, JavaScript execution, parallel runs and the most common exceptions.

Selenium WebDriver talks to the browser through a driver; since Selenium 4.6 the bundled Selenium Manager downloads the matching driver automatically, so you rarely install chromedriver by hand now. For the bigger picture see the automation testing questions, the SDET questions and how to crack a QA testing interview.

Version in these answersSelenium 4 (W3C WebDriver protocol), Java 17+ and Python 3.10+
SupportsChrome, Firefox, Edge, Safari; Java, Python, C#, JavaScript, Ruby, Kotlin
Often paired withTestNG or JUnit 5, pytest, Maven, Jenkins or GitHub Actions

A minimal, correct Selenium test

Interviewers sometimes ask you to write the smallest correct test. Note that it uses an explicit wait, not Thread.sleep, quits the driver in a finally block or fixture so browsers are never left running, and asserts on something observable.

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()          # Selenium Manager resolves the driver
    d.implicitly_wait(0)            # rely on explicit waits only
    yield d
    d.quit()

def test_search_shows_results(driver):
    driver.get('https://example.com/search')
    driver.find_element(By.NAME, 'q').send_keys('laptop')
    driver.find_element(By.CSS_SELECTOR, 'button[type=submit]').click()
    results = WebDriverWait(driver, 10).until(
        EC.visibility_of_all_elements_located((By.CSS_SELECTOR, '.result-card'))
    )
    assert len(results) > 0

Selenium Interview Questions and Answers: questions with worked answers

  1. 1

    What is Selenium and what are its components?

    easy

    Selenium is an open-source suite for automating browsers. Selenium WebDriver is the core API: it sends commands to a browser driver (chromedriver, geckodriver, msedgedriver) over the W3C WebDriver protocol, and the driver controls the real browser. Selenium Grid distributes tests across machines and browsers. Selenium IDE is a record-and-playback browser extension for quick prototypes. The older Selenium RC is obsolete. Selenium automates web UIs only: it cannot drive desktop applications or handle native OS dialogs, and it offers no built-in reporting or test runner, so you pair it with TestNG, JUnit or pytest.

  2. 2

    What locator strategies does Selenium offer, and how do you choose between them?

    medium

    The By strategies are id, name, className, tagName, linkText, partialLinkText, CSS selector and XPath, and Selenium 4 adds relative locators such as above and toRightOf. Prefer, in order: a stable id or a dedicated data-testid attribute, then a short CSS selector, then XPath only when you must navigate to a parent or match by text. Avoid long absolute XPaths like /html/body/div[2]/div/div[3]/a, which break with any layout change, and avoid brittle indexes. Ask developers to add test ids. A locator should be unique, readable and tied to meaning, not to styling classes that designers change.

    java
    driver.findElement(By.id("email"));
    driver.findElement(By.cssSelector("[data-testid='submit-order']"));
    driver.findElement(By.xpath("//tr[td[text()='Asha']]//button[@title='Delete']"));
    driver.findElement(RelativeLocator.with(By.tagName("input")).below(By.id("email")));
  3. 3

    What is the difference between implicit, explicit and fluent waits? Which should you use?

    medium

    An implicit wait sets a global polling timeout for every findElement call; it is applied implicitly and mixing it with explicit waits produces unpredictable total wait times, so Selenium's own guidance is not to combine them. An explicit wait, WebDriverWait with an ExpectedCondition, polls for one specific condition on one element, such as clickable or visible, up to a timeout, and is the recommended approach. A fluent wait is an explicit wait with a custom polling interval and a list of exceptions to ignore. Thread.sleep waits a fixed time whether needed or not, making tests slow and still flaky. Use explicit waits for conditions that matter, and keep implicit at zero.

    java
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    WebElement btn = wait.until(ExpectedConditions.elementToBeClickable(By.id("pay")));
    btn.click();
    
    Wait<WebDriver> fluent = new FluentWait<>(driver)
        .withTimeout(Duration.ofSeconds(30))
        .pollingEvery(Duration.ofMillis(500))
        .ignoring(NoSuchElementException.class);
    WebElement toast = fluent.until(d -> d.findElement(By.cssSelector(".toast")));
  4. 4

    What causes StaleElementReferenceException and how do you handle it?

    medium

    A WebElement holds a reference to a specific DOM node. If the page re-renders and replaces that node, for example after an AJAX update or a React re-render, the reference is stale and any call on it throws this exception. Fix it by re-locating the element after the change instead of caching it, using an explicit wait on the new state such as ExpectedConditions.refreshed or stalenessOf for the old element, and storing locators (By) in page objects rather than element objects. A blind retry loop works as a last resort but can hide real timing problems.

  5. 5

    Explain the Page Object Model and write a short example.

    medium

    POM wraps each page or component in a class that exposes user actions and hides locators, so tests read as business steps and a UI change is fixed in one place. Rules of good design: page methods perform actions and return either the next page object or data, assertions generally stay in tests, locators are private, and waits live inside the page class. Components such as a header or a table can be their own classes. PageFactory with @FindBy exists in Java but is largely discouraged now in favour of plain By locators and explicit waits.

    java
    public class LoginPage {
        private final WebDriver driver;
        private final WebDriverWait wait;
        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;
            this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        }
    
        public DashboardPage loginAs(String user, String pass) {
            wait.until(ExpectedConditions.visibilityOfElementLocated(email)).sendKeys(user);
            driver.findElement(password).sendKeys(pass);
            driver.findElement(submit).click();
            return new DashboardPage(driver);
        }
    }
  6. 6

    How do you handle multiple windows, tabs, frames and alerts?

    medium

    Each window has a handle. Store the current handle, trigger the action, wait for the window count to change, then switch to the new handle and switch back when done. For iframes, switch into the frame by element, id or index with switchTo().frame and return with defaultContent() or parentFrame(); elements inside a frame cannot be found until you switch. JavaScript alerts are handled with switchTo().alert() to accept, dismiss, read text or send keys, after waiting for alertIsPresent. Selenium 4 also offers newWindow(WindowType.TAB) to open a tab directly. Native OS file dialogs are not controllable; use sendKeys with the file path on the input element instead.

    java
    String original = driver.getWindowHandle();
    driver.findElement(By.linkText("Open report")).click();
    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.numberOfWindowsToBe(2));
    for (String h : driver.getWindowHandles()) {
        if (!h.equals(original)) { driver.switchTo().window(h); break; }
    }
    // ... assertions ...
    driver.close();
    driver.switchTo().window(original);
    
    driver.switchTo().frame(driver.findElement(By.id("payment-frame")));
    driver.findElement(By.id("card")).sendKeys("4111111111111111");
    driver.switchTo().defaultContent();
  7. 7

    A click throws ElementClickInterceptedException or ElementNotInteractableException. What are the causes and fixes?

    medium

    Intercepted means another element, such as a cookie banner, a loading overlay or a sticky header, receives the click at that point. Wait for the overlay to disappear (invisibilityOfElementLocated), dismiss the banner, or scroll the element into view and wait for elementToBeClickable. Not interactable means the element exists but is hidden, disabled, zero-sized, or covered by an animation. Check that the right element is targeted, wait for visibility, and make sure you are in the correct frame. A JavaScript click is a last resort, because it skips the real user behaviour and can pass a test that a user could not complete.

  8. 8

    How do you run JavaScript and when is it appropriate?

    easy

    Cast the driver to JavascriptExecutor and call executeScript. Appropriate uses are scrolling to an element or the page bottom, reading values the DOM API does not expose, clearing local storage, or retrieving computed values for assertions. Avoid it for clicking and typing in normal flows because it bypasses actionability checks that make tests realistic. Arguments are passed after the script and referenced as arguments[0], and the script can return values.

    java
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].scrollIntoView({block:'center'});", element);
    Long height = (Long) js.executeScript("return document.body.scrollHeight;");
    js.executeScript("window.localStorage.clear();");
  9. 9

    How do you handle dropdowns, including custom ones?

    easy

    For a native select element use the Select class: selectByVisibleText, selectByValue or selectByIndex, and getFirstSelectedOption to assert. Custom dropdowns built from div and li elements are not select elements, so Select throws UnexpectedTagNameException. Treat them as ordinary elements: click to open, wait for the options to be visible, then click the option by text with a locator such as an XPath on the list item. Verify the displayed selection afterwards. For type-ahead widgets, send keys and wait for the suggestion list.

    python
    from selenium.webdriver.support.ui import Select
    Select(driver.find_element(By.ID, 'country')).select_by_visible_text('India')
    
    # custom dropdown
    driver.find_element(By.CSS_SELECTOR, '.dropdown-toggle').click()
    WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//ul[@role='listbox']/li[normalize-space()='Mumbai']"))
    ).click()
  10. 10

    What is the difference between findElement and findElements, and between get and navigate().to()?

    easy

    findElement returns the first match or throws NoSuchElementException; findElements returns a list, which is empty if nothing matches, so it is the safe way to test for absence. driver.get(url) and navigate().to(url) both load a page and wait for the load event; navigate() additionally exposes back, forward and refresh, and in Selenium both behave the same for loading. close() closes the current window, whereas quit() ends the session and closes every window, and should be called in teardown. getText returns visible text, getAttribute reads an HTML attribute or property, and in Selenium 4 getDomProperty and getDomAttribute make the distinction explicit.

  11. 11

    What is Selenium Grid and how do you run tests in parallel safely?

    hard

    Selenium Grid 4 has a hub-node style or a fully distributed mode with router, distributor, session map, queue and nodes; it runs sessions on remote machines and containers, letting one suite cover several browsers and operating systems at once. To run tests in parallel safely, every test must own its own driver instance, held in a ThreadLocal in Java or a fixture in pytest, tests must be independent with no shared mutable state or ordering, and test data must not collide, for example by generating unique users. Configure parallelism in TestNG with parallel methods and thread-count, or with pytest-xdist. Cloud grids and Selenium Grid in Docker are common setups.

    java
    public class DriverFactory {
        private static final ThreadLocal<WebDriver> DRIVER = new ThreadLocal<>();
    
        public static WebDriver start() {
            ChromeOptions opts = new ChromeOptions();
            opts.addArguments("--headless=new");
            WebDriver d = new ChromeDriver(opts);   // or new RemoteWebDriver(gridUrl, opts)
            DRIVER.set(d);
            return d;
        }
        public static WebDriver get() { return DRIVER.get(); }
        public static void stop() { DRIVER.get().quit(); DRIVER.remove(); }
    }
  12. 12

    Why are Selenium tests flaky, and how do you fix flakiness?

    hard

    Common causes: timing (acting before the page is ready), brittle locators, shared state between tests, test data that changes, animations, third-party scripts and unstable environments. Fixes: explicit waits on real conditions, stable test-id locators, isolated tests that create their own data through the API instead of the UI, resetting state between tests, disabling animations in the test environment, and mocking unreliable third parties. Capture screenshots and browser logs on failure, track the flaky rate per test, quarantine repeat offenders instead of adding blind retries, and fix root causes. A retry mechanism may hide real intermittent product bugs.

  13. 13

    How do you take a screenshot on failure and read browser console logs?

    medium

    Cast to TakesScreenshot and call getScreenshotAs. Hook it into the test framework's failure callback: a TestNG listener's onTestFailure, a JUnit 5 extension, or a pytest hook using the makereport hook and a fixture. For console logs, Selenium 4 exposes BiDi log APIs, and in Chrome you can read browser logs by enabling logging preferences. Attach artefacts to the report so a failure in CI can be diagnosed without rerunning. Also save the page source and the current URL.

    java
    public class FailureListener implements ITestListener {
        @Override
        public void onTestFailure(ITestResult result) {
            WebDriver d = DriverFactory.get();
            File src = ((TakesScreenshot) d).getScreenshotAs(OutputType.FILE);
            try {
                Files.copy(src.toPath(), Path.of("target/screens/" + result.getName() + ".png"),
                           StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) { throw new UncheckedIOException(e); }
        }
    }
  14. 14

    Compare Selenium, Cypress and Playwright.

    medium

    Selenium supports the most languages and browsers, including Safari through its driver, and has a large ecosystem, but needs explicit synchronisation and more setup. Cypress runs inside the browser with automatic retries and a good debugging UI, but it is JavaScript and TypeScript only and historically limited for multi-tab scenarios. Playwright supports several languages, has auto-waiting actionability checks, built-in tracing, network interception and parallel isolation through browser contexts, and is increasingly popular for new projects. Pick Selenium for broad language and legacy support, or when a Grid already exists; pick Playwright or Cypress for faster authoring in new JavaScript-heavy stacks.

  15. 15

    How do you test a table of data, such as verifying a row exists and sorting works?

    medium

    Read the table into a list of row objects rather than indexing cells in assertions. Locate rows with a relative XPath or CSS that matches on cell text, then read the adjacent cells. For sorting, click the header, wait for the table to refresh (staleness of the first row, or a spinner disappearing), read the column into a list and compare against a sorted copy, taking care with numeric versus text comparison. For pagination, loop until the Next control is disabled. Where possible verify the underlying data by API, and use the UI test only for presentation behaviour.

    python
    def column_values(driver, col_index):
        cells = driver.find_elements(By.CSS_SELECTOR, f'table#orders tbody tr td:nth-child({col_index})')
        return [c.text.strip() for c in cells]
    
    driver.find_element(By.CSS_SELECTOR, 'th[data-col=amount]').click()
    WebDriverWait(driver, 10).until(lambda d: column_values(d, 3) != before)
    amounts = [float(v.replace(',', '')) for v in column_values(driver, 3)]
    assert amounts == sorted(amounts)
  16. 16

    How do you handle authentication pop-ups, file uploads and downloads?

    medium

    For HTTP basic authentication, put the credentials in the URL (https://user:pass@host) where supported, or in Selenium 4 register credentials through the BiDi or DevTools network APIs. For file uploads, call sendKeys with the absolute file path on the input of type file, even if it is visually hidden, rather than trying to drive the OS dialog. For downloads, set the browser's download directory in options, trigger the download, then wait with a polling loop until the file appears and the temporary partial file is gone, and assert on name and size. Run it in CI with a clean download folder.

  17. 17

    What are the new features in Selenium 4 that you would mention in an interview?

    easy

    The W3C WebDriver protocol is now the standard, replacing the older JSON wire protocol. Relative locators find elements by position, new window and tab APIs create and switch directly, element-level screenshots are supported, the Chrome DevTools Protocol bridge and WebDriver BiDi give network interception, console log capture and geolocation emulation, the Grid was redesigned with observability and Docker support, and Selenium Manager removes manual driver management. The Selenium IDE was also revamped. Knowing why each helps, such as BiDi making log capture and request mocking possible, matters more than listing them.

Frequently asked questions

Which language is best for Selenium?

Java has the largest enterprise and interview footprint in India, while Python is quicker to learn and write. Pick the language your target employers use and learn its test framework (TestNG or JUnit, or pytest).

Do I still need to install chromedriver?

Usually not. Since Selenium 4.6 the Selenium Manager resolves and downloads the right driver automatically. You may still pin a driver in locked-down CI environments.

Is Selenium dead because of Playwright?

No. Selenium remains widely deployed and is a W3C-standard approach. Many new projects choose Playwright, so knowing both concepts, auto-waiting and explicit waits, is useful.

How many years of experience do Selenium questions assume?

Freshers are asked locators, waits and POM basics. Experienced candidates are asked framework design, parallel execution, Grid, flaky test strategy and CI integration.

Related guides

More in Role-wise Interview Questions by Job and Tech Stack

See all in this section