Selenium Interview Prep
72 questions with the answer an interviewer actually wants to hear, organised by level. Each answer links to the lesson that goes deeper.
Junior: Fundamentals
Questions for entry-level and first-year automation roles. Interviewers want correct definitions and one concrete example each.
1.What is Selenium WebDriver?
A library that lets code control a real browser through the W3C WebDriver protocol. Your test sends commands (open URL, find element, click) to a browser-specific driver such as chromedriver, which executes them in the browser. It is not a test framework: you pair it with JUnit, pytest, NUnit or Mocha for structure and assertions.
2.Explain the Selenium architecture.
Four parts: your language binding turns method calls into HTTP requests; the W3C WebDriver protocol defines those requests; the vendor's browser driver (chromedriver, geckodriver, msedgedriver, safaridriver) is an HTTP server that translates them into browser actions; the browser does the work. Selenium Manager sits before the driver to make sure the right executable exists. Grid sits between binding and driver to route commands to remote machines. BiDi adds a WebSocket alongside for events.
3.What are the different locator strategies?
id, name, className, tagName, linkText, partialLinkText, cssSelector and xpath, plus Selenium 4's relative locators (above, below, toLeftOf, toRightOf, near). Prefer a dedicated test id or a stable id, then name, then semantic CSS, then text, and use XPath when you need text matching or upward traversal.
4.What is the difference between findElement and findElements?
findElement returns the first match and throws NoSuchElementException if none. findElements returns a list of all matches, empty if none, and never throws. Use findElements for counting, iterating, and existence checks.
5.What is an implicit wait?
A session-wide timeout that makes every findElement retry until the element appears or the timeout expires. It is simple but blunt: it also slows every negative check and interacts badly with explicit waits. Most teams keep it at zero.
6.What is an explicit wait?
A wait tied to a specific condition and timeout, using WebDriverWait with an expected condition such as visibilityOfElementLocated or elementToBeClickable. It polls until the condition passes and then returns the element. It is the recommended synchronisation mechanism.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));WebElement btn = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));btn.click();7.Why is Thread.sleep bad practice?
It always waits the full time even if the app was ready earlier, and it still fails when the app is slower than the guess. Explicit waits proceed as soon as the condition holds and fail with a clear timeout otherwise.
8.What is the difference between close() and quit()?
close() closes the current window or tab only. quit() closes every window, ends the session and stops the driver process. Always quit() in cleanup, or CI machines accumulate orphaned browser processes.
9.How do you handle a JavaScript alert?
Switch to it with driver.switchTo().alert(), then accept(), dismiss(), getText() or sendKeys(). Wait for it with ExpectedConditions.alertIsPresent since it may appear a moment after the click. The unhandledPromptBehavior capability defines what happens to alerts you did not handle.
10.How do you work with an iframe?
Switch the driver's context into it with switchTo().frame(element or name or index), interact, then switchTo().defaultContent() to return to the main document. Wrap the work in try/finally so you always return.
11.What is a StaleElementReferenceException?
The WebElement you hold refers to a DOM node that was removed or replaced, typically because the framework re-rendered. Re-find the element after the change instead of caching it; a small retry helper handles the common case.
12.What is Selenium Manager?
A binary bundled with Selenium 4.6+ that detects the installed browser and downloads the matching driver into a cache automatically. From 4.11 it can also download the browser itself for a pinned version. It removed the need to manage chromedriver paths.
13.How do you take a screenshot?
Cast the driver to TakesScreenshot (Java) or call save_screenshot (Python), takeScreenshot (JavaScript), GetScreenshot (C#). Selenium 4 also supports screenshots of a single element. Capture on test failure in a framework hook.
File png = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);Files.copy(png.toPath(), Path.of("failure.png"));14.How do you select a value from a dropdown?
For a native select element, use the Select helper: selectByVisibleText, selectByValue or selectByIndex. For custom dropdowns built from divs, click the trigger and then click the option by text with a wait for visibility.
15.How do you upload a file?
Send the absolute path to the input[type=file] element with sendKeys. Do not click the button, because the OS dialog is outside the browser. On a Grid, set LocalFileDetector on RemoteWebDriver so the file is transferred first.
16.What is the Page Object Model?
A design pattern where each page or component gets a class that owns its locators and exposes methods named for user actions. Tests call those methods instead of locating elements. When the UI changes, you fix one class.
17.What is headless mode?
Running the browser without a visible window. Chrome uses --headless=new, Firefox -headless. It is faster and works on CI servers with no display. Set an explicit window size because there is no screen to maximise to.
18.What is the difference between getText() and getAttribute("value")?
getText() returns the rendered visible text between an element's tags. For inputs the typed content is the value property, read with getAttribute("value") or getDomProperty("value"). Hidden elements return empty text; use textContent for those.
19.How do you navigate back, forward and refresh?
driver.navigate().back(), forward() and refresh(). They use browser history. A refresh invalidates all WebElement references, so re-find afterwards.
20.What browsers does Selenium support?
Chrome, Edge, Firefox and Safari through vendor-maintained drivers, plus Chromium-based browsers via chromedriver. Older Internet Explorer support exists in Selenium 4 through IE mode in Edge. Mobile browsers and native apps are covered by Appium, which speaks the same protocol.
Mid-Level: Building Suites
Questions for engineers expected to own a suite: design, synchronisation, CI, and the details that separate working code from maintainable code.
1.Why should implicit and explicit waits not be combined?
The driver applies the implicit wait inside every findElement, including the ones an explicit wait polls, so timeouts stack unpredictably. Negative checks (element should be absent) always burn the full implicit timeout. Set implicit wait to zero and use explicit waits with specific conditions.
2.What is FluentWait and how does it differ from WebDriverWait?
FluentWait is the general wait with configurable timeout, polling interval and a set of exceptions to ignore while polling. WebDriverWait is a FluentWait specialised for WebDriver with defaults of 500 ms polling and ignoring NoSuchElementException. You use FluentWait's builder when you need a faster poll or to ignore StaleElementReferenceException.
Wait<WebDriver> wait = new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(15)) .pollingEvery(Duration.ofMillis(200)) .ignoring(StaleElementReferenceException.class);3.How do you write a custom expected condition?
Any function of the driver that returns a truthy value when satisfied and null/false otherwise. Return the useful value (element, list, text) so the caller can use it. Give it a description for readable timeout messages. Typical customs: attribute equals, count at least N, text stable across two polls.
4.What are the page load strategies and when would you change the default?
normal waits for the load event, eager for DOMContentLoaded, none returns immediately. Use eager for single-page apps and pages with slow third-party assets, paired with explicit waits for the elements you need. Use none when you need full control or a page never fires load.
5.How do you make tests run in parallel safely?
Give every test its own driver, never a shared static one. In Java use a ThreadLocal behind a manager class and remove() after quit(); in pytest use function-scoped fixtures with xdist workers; in NUnit use per-test instances. Isolate test data per test, avoid order dependence, and size parallelism to CPU and memory.
6.Design a driver factory.
One method reads configuration (browser, headless, grid URL, timeouts) from environment variables with defaults, builds the matching Options, and returns either a local driver or a RemoteWebDriver. It sets window size, page load timeout and, for remote, LocalFileDetector. All tests call it; nothing else constructs drivers.
7.How do you handle a new window or tab?
Capture the current handle and the set of handles before the click. After clicking, wait for the handle count to increase, compute the set difference to find the new handle, switch to it. When done, close it and switch back to the original before any other command.
8.How do you interact with Shadow DOM?
Locate the host element, call getShadowRoot() to obtain the shadow tree as a search context, then use CSS selectors from it. Repeat for nested hosts. XPath cannot cross shadow boundaries and closed shadow roots are unreachable.
9.What are relative locators and when are they appropriate?
Selenium 4 locators that find an element by position relative to another: above, below, toLeftOf, toRightOf, near. They use rendered bounding boxes, so they break on layout changes and small viewports. Use them when no stable attribute exists and you cannot add a test id.
10.Explain ElementClickInterceptedException and how you fix it.
The driver computed the click point and found another element on top: a sticky header, modal or toast. Fixes in order: wait for the overlay to disappear, scroll the target to the centre with scrollIntoView({block:'center'}), then as a logged fallback a JavaScript click.
11.How do you reuse a login session across tests?
Log in once, export cookies (or the token in localStorage) to a file, and before each test navigate to the domain, add the cookies, then go to the target page. Regenerate on expiry. Alternatively call the login API and set the resulting cookie directly.
12.How do you verify a downloaded file?
Configure a known download directory in the browser options, trigger the download, poll the filesystem until the file exists and no partial file remains, then parse it with a CSV or PDF library and assert on headers and distinctive values. On a Grid, use managed downloads (se:downloadsEnabled) to fetch the file from the node.
13.What goes into a good failure report?
Screenshot, page source, current URL, console errors and failed network requests from BiDi, the assertion message, and, on a Grid, the session id linking to video. Captured in the framework's after-hook on failure only, uploaded as a CI artifact or attached to Allure.
14.How do you structure a Selenium job in CI?
Headless with explicit window size, pinned or cached browser via Selenium Manager, parallelism matched to runner resources, timeouts at job and test level, artifacts on failure, secrets from the CI store. For version control or video, run the official Selenium image as a service container and use RemoteWebDriver.
15.What is the difference between Page Factory and plain Page Objects?
Page Factory (Java) initialises fields annotated with @FindBy as lazy proxies that locate on each access. Plain page objects hold By locators and call findElement explicitly. Page Factory is terser; explicit By fields are more flexible with waits and are the common recommendation today.
16.How do you test a page behind HTTP basic auth?
Enable BiDi and register an authentication handler with the credentials before navigating; it answers the challenge for matching requests in Chrome, Edge and Firefox. Embedding credentials in the URL is a legacy fallback that leaks into logs.
17.How do you get console errors from the browser?
With BiDi enabled, driver.script().addConsoleMessageHandler and addJavaScriptErrorHandler receive entries as they happen, cross-browser. The old driver.manage().logs().get("browser") API is Chromium-only and not part of the W3C spec.
18.What is data-driven testing and how do you implement it?
Running one test body against many input rows. TestNG DataProvider, JUnit 5 @ParameterizedTest with CSV or method sources, pytest.mark.parametrize, NUnit TestCaseSource. Keep data in files when it is large or shared, and name rows so failures identify the case.
19.How would you migrate a Selenium 3 suite to Selenium 4?
Bump to the latest 4.x. Replace DesiredCapabilities with Options and move vendor keys under prefixed maps. Convert Java timeouts to Duration. Replace driver path management with Selenium Manager. Remove find_element_by_* (Python) and findElementByX (Java). Run the suite twice in CI and fix the timing bugs stricter W3C behaviour exposes.
20.How do you scroll to an element?
Usually you do not; Selenium scrolls before interacting. When needed: scrollIntoView({block:'center'}) via JavaScript to avoid sticky headers, or Actions.scrollToElement (Selenium 4.2+) for real wheel events. For infinite scroll, loop scrolling to the bottom and wait for the item count to grow, with a cap.
Senior: Architecture and Strategy
Questions for senior SDET and lead roles. Interviewers want trade-offs, real examples, and awareness of where the ecosystem is going.
1.Selenium or Playwright for a new project? Defend your answer.
It depends on four things: team language, browser and device matrix, existing infrastructure, and wait discipline. A Java or C# team with a Grid and Safari or mobile requirements gets more from Selenium: vendor-maintained drivers, W3C standard, Appium reuse, Kubernetes-scale Grid. A TypeScript team starting fresh with Chromium-first needs benefits from Playwright's speed, auto-wait and integrated runner. In 2026 Playwright leads new-project surveys, Selenium leads installed base and breadth. The transferable asset is test design, so I would choose by team fit and keep page objects and data strategy portable.
2.What is WebDriver BiDi and how has it changed your suites?
A W3C bidirectional protocol over a WebSocket alongside classic WebDriver, letting the browser push events and accept interception commands. Practically: every test now fails on uncaught JavaScript errors, basic auth is one line, third-party requests are blocked for speed, API responses are mocked for empty and error states, and a network-idle wait replaced sleeps after API-triggering actions. It works across Chrome, Edge and Firefox, unlike CDP, and Selenium 5 removes CDP-only paths.
3.When would you still use CDP?
Performance metrics from the Performance domain, some Chromium-only emulation, and older suites that already isolate CDP calls. I would send raw commands by name rather than versioned typed modules, keep them behind an interface with a BiDi implementation next to it, and pin the Chrome version in CI so the DevTools package and browser move together.
4.Describe a flaky test you fixed and the method you used.
The answer should follow the method: classify from evidence (timing, state, order, environment, product bug), reproduce deliberately with repetition and CPU or network throttling, fix the root cause with the right wait or isolation, verify with hundreds of runs, and remove the quarantine tag. A strong example includes the wrong wait condition, the correct one, and a product bug found along the way.
5.How would you scale a suite from 200 to 2,000 tests?
Measure first: commands and wait time per test. Skip UI login and setup via cookies and APIs. Remove sleeps, zero the implicit wait, use eager page load, block third-party traffic. Then parallelise with a thread-safe driver factory, shard by historical duration across CI jobs, and run browsers on a Grid, ideally Dynamic Grid on Kubernetes with failure-only video. Finally shrink: push validation logic down to unit and API tests and keep Selenium for journeys only.
6.Explain Selenium Grid 4 architecture and what changed in 2026.
Router (entry), Session Queue, Distributor (matching), Session Map, Event Bus (ZeroMQ) and Nodes. In 2026: Grid 4.41 added a native Kubernetes session factory that provisions Pods per session without Docker, a session event API tests can fire, and event-driven video with failure-only upload; 4.44 and 4.45 made the Distributor, Session Map and Queue Redis-backed for high availability; Traefik replaced NGINX in the Helm chart; images are mirrored to GHCR.
7.Page Objects versus Screenplay: when do you switch?
Page Objects are right for most suites and small teams. Symptoms that justify Screenplay: page classes with dozens of methods, compound methods crossing pages, several teams contributing, and multi-actor scenarios. Screenplay's composition (tasks of interactions, questions for state) scales and reports better but costs ceremony. Migrate incrementally: wrap existing page objects as interactions and write new features in Screenplay.
8.How do you decide what to test with Selenium versus lower layers?
Apply the pyramid honestly: form validation rules and business logic belong in unit tests; API contracts in API tests; Selenium covers journeys and integration points that only a browser exercises (navigation, rendering, JavaScript interaction, auth flows). Review quarterly and delete browser tests that duplicate lower coverage and have never failed. Keep a small smoke set per commit and the full set nightly.
9.How do you use AI in a Selenium suite responsibly?
Generate page objects and test skeletons from real DOM with a prompt that states locator policy and shows an existing page object, then review as a pull request. Self-healing locators only with every heal logged and fixed in source. Visual AI for noise reduction in screenshot diffs at stable states. LLM triage over an evidence bundle (screenshot, page source, console, network) collected via BiDi. Autonomous test generation stays exploratory, not in the regression suite.
10.Design a cross-browser strategy for Chrome, Firefox, Edge, Safari and mobile.
Self-hosted Grid (Docker or Kubernetes) for the bulk Chrome runs on every pull request; a cloud vendor for the nightly matrix including real Safari on macOS and real iOS and Android via Appium. One driver factory with vendor-prefixed options, tunnels for private environments, results marked from teardown. BiDi for logs and interception where the vendor supports it; test IDs and ARIA-based locators so the same page objects hold across engines.
11.What do you monitor on a Grid in production?
Queue length (drives autoscaling), slot utilisation, session creation latency, session failures by reason, node health, and per-command latency via OpenTelemetry tracing. Structured JSON logs to Loki or Elasticsearch. Alerts on queue age and on nodes stuck in draining. Video and assets storage growth, mitigated with failure-only upload.
12.How would you handle a WebAuthn or passkey login flow?
Add a virtual authenticator to the session (CTAP2, internal transport, resident keys, user verified) so the browser answers WebAuthn prompts without a dialog. Register through the UI to test sign-up; seed a credential with a known key to test sign-in; flip isUserVerified to test failure paths. Safari lacks the API, so cover it differently.
13.Explain how you keep locators stable across a redesign.
Negotiate test IDs on interactive elements with a naming convention enforced in code review. Prefer ids and names, then ARIA attributes, then product text for critical labels. Ban absolute XPath, styling classes and indexes in review. Keep locators in page objects, verify uniqueness while writing, and scope searches to containers. A redesign then becomes a page-object diff, not a test rewrite.
14.What are the runtime floors and notable removals a team upgrading to Selenium 4.48 must know?
Java 11 minimum (Java 8 ended at 4.13), Python 3.10 minimum (3.9 ended at 4.37), .NET packages strongly signed and async since 4.41 and 4.44, Firefox CDP removed in 4.29, Java's deprecated logging classes removed in 4.45, Python's FirefoxBinary removed in 4.40. The upgrade path is to the latest 4.x directly, then fix capabilities and timeouts.
15.How do you mock backend states in end-to-end tests without a mock server?
BiDi network interception: intercept the endpoint at beforeRequestSent and provideResponse with the status and body for the empty, error or edge-case state. Record real responses first so mocks match the contract, remove intercepts between scenarios, and keep one unmocked test per endpoint against the real backend.
16.How do you keep CI-only flakiness out of the suite?
Explicit window size, pinned browser via Selenium Manager, adequate shared memory in containers, fonts installed, parallelism sized to resources, deterministic sharding, and Selenium Manager cache warmed. Treat CI-only failures as timing bugs masked by fast laptops, not as noise. Never blanket-retry.
17.What would your first month look like inheriting a 1,500-test legacy suite?
Week one: get it running in CI with evidence on failure and measure duration and flakiness per test. Week two: quarantine the worst offenders with a deadline, fix the driver factory and thread safety, zero the implicit wait. Week three: cookie-based login, remove sleeps, block third parties, enable BiDi error capture in a base class. Week four: shard and parallelise, delete duplicated coverage, publish a dashboard. Communicate the plan and the numbers each week.
18.How does Selenium's governance differ from Playwright's and why does it matter?
Selenium is a Software Freedom Conservancy project implementing W3C standards; browser vendors ship the drivers. Playwright is a Microsoft project that ships patched browser builds and its own protocol. For enterprises this affects longevity risk, standards alignment, and how compatibility is guaranteed when browsers update every two weeks.
19.Describe how you would test an Electron desktop application.
Electron embeds Chromium, so chromedriver drives it. Selenium 4.45 Java added ElectronOptions and ElectronDriver; in other bindings set ChromeOptions.setBinary to the app executable and use a chromedriver matching the embedded Chromium. Same page objects, locators and waits apply.
20.What is your position on test retries?
Retries make a flaky suite look green and remove the signal needed to fix it. If used at all: only on tests tagged flaky, with retry counts reported as a metric, never on tests with side effects on shared state, and with a deadline to fix or delete the test.
Scenario Questions
Open-ended problems interviewers use to see how you think. There is no single right answer; the structure of the answer is what they grade.
1.A test clicks Save and asserts a success toast. It passes 95% of the time. Walk me through your investigation.
Collect evidence from failures: screenshot, console, network. If the toast is absent but the save succeeded, it is a timing bug: the toast appears and disappears within the polling window, or the assertion ran before the API returned. Reproduce with repetition and throttling. Fix by waiting for the durable signal (the saved value, the URL, a network response) rather than the transient toast, or lengthen the toast in test mode. If the save sometimes fails, it is a product bug: check the failed network request and file it.
2.The product team wants the full suite on every pull request but it takes 45 minutes. What do you do?
Measure per-test time and commands. Skip UI login via cookies. Remove sleeps and set eager page load. Block third-party requests. Parallelise with a thread-safe driver factory and shard across CI jobs by duration. Move validation tests down the pyramid. Define a 5-minute smoke set for pull requests and run the rest nightly and on merge. Report the before and after numbers.
3.Your suite must run on Chrome 118 for a regulated customer and on latest Chrome for everyone else. How?
Selenium Manager with browserVersion pinned to 118 in one CI job and 'stable' in another; it downloads Chrome for Testing builds and matching drivers. Or run Docker images tagged for each version on a Grid. Same test code, different configuration. Review the pin quarterly so the regulated run does not silently become obsolete.
4.Developers say the tests are 'too brittle' and want to stop writing them. How do you respond?
Quantify: which tests break, on which changes, and why. Usually locators tied to styling and structure. Propose test IDs with a naming convention, page objects so a change is one edit, and a review checklist for locators. Offer to pair on the next feature to show the cost is small. Agree metrics: locator-related failures per month.
5.A checkout test needs an order in 'shipped' state, which takes a warehouse job 24 hours to produce. How do you test it?
Do not wait for the job. Options in order: an API or database seed that creates a shipped order for the test user; a test-only endpoint the job exposes; BiDi network mocking of the orders endpoint to return a shipped state for the UI test. Keep one integration test in a nightly pipeline against a real shipped order.
6.The security team asks you to test that the app never leaks the session token into analytics requests. How?
Enable BiDi, observe every request with onBeforeRequestSent, and assert that no request to analytics hosts contains the token in URL, headers or body. Run it as part of the login journey test. Also block those hosts in normal tests for speed, but keep this one unblocked.
7.A new hire wants to add Thread.sleep(5000) 'just to be safe' before every assertion. What do you say?
Explain that it adds five seconds to every test unconditionally and still fails when the app is slower than five seconds. Show the explicit wait for the actual condition, and the network-idle or text-stable conditions for the hard cases. Add a lint rule or review check against sleep in test code.
8.Tests pass on macOS laptops and fail on Linux CI with layout-related errors. Diagnose.
Window size (headless default), missing fonts changing text width and wrapping, device pixel ratio, and browser version differences. Set an explicit window size, install fonts in the CI image or use the official Selenium images, pin the browser, and compare screenshots from both environments.
9.Leadership wants to 'add AI' to the test suite. What do you propose?
Three concrete, measurable pilots: assistant-generated page objects from real DOM with review, reducing authoring time; LLM triage over BiDi-collected evidence, reducing time to classify failures; visual AI on a handful of layout-critical pages. Explicitly exclude autonomous test generation from the regression suite and require logged, reviewed heals if self-healing is trialled.
10.Your Grid runs out of capacity every morning at 9 when all teams push. Options?
Autoscale: Dynamic Grid on Kubernetes with KEDA scaling Node deployments from queue length, capped by a max replica count and cluster budget. Shorter sessions via cookie login and session timeouts to free slots. Stagger schedules or prioritise pull-request smoke runs over full suites. Monitor queue age and alert.
11.A test needs to verify an email was sent after sign-up. Where does Selenium stop?
Selenium drives the browser; email is outside it. Use a test mail service or an API (Mailhog, Mailpit, a provider's sandbox) to fetch the message, extract the link or code, and continue the browser flow with it. Keep the browser part and the mail part in separate steps with clear failure messages.
12.You inherit tests that assert page text in five languages with hard-coded strings. Improve them.
Locate by test IDs and ARIA rather than text, and assert against the app's own translation resources loaded in the test, keyed by message id. Where text must be asserted, parametrise by locale from a data source. Run one locale per pull request and all locales nightly.
Live coding tasks
Senior interviews usually include two or three hands-on tasks. Practise on these debugging challenges first. Each has progressive hints and a reference solution.
- Fix the Flaky Login Test beginner · 10 min
- Stale Elements in a Delete Loop intermediate · 15 min
- Replace Brittle Locators beginner · 10 min
- The Payment iFrame Bug intermediate · 10 min
- The 30-Second Negative Check intermediate · 10 min
- Extract a Page Object intermediate · 20 min
- The Wrong Tab intermediate · 10 min
- Tests Interfere When Run in Parallel advanced · 20 min
- The Dropdown That Is Not a Select beginner · 10 min
- Catch the JavaScript Error the Test Missed advanced · 15 min
How to use this page
- Answer out loud first. Open the answer only after you have said yours. Interviews test recall under pressure, not recognition.
- Bring examples. Every senior answer should include one concrete story from a real suite: a flaky test you fixed, a grid you scaled, a migration you led.
- Know the modern landscape. Expect to be asked why you would choose Selenium over Playwright, what BiDi changes, and how you use AI tools responsibly. The Selenium 4, BiDi & Beyond chapter covers exactly that.
- Test yourself. The quizzes track your best score per topic so you can see where to revise.