Selenium WebDriver interview questions
Updated 2026-11-12 · 12 min read
Thirty-two Selenium questions with short working Java code, written for people who have used Selenium in a project: waits, flaky tests, locators, real-world problems and framework design.
Code samples use Java and Selenium 4. They assume driver is a WebDriver and that you have imported the usual classes from org.openqa.selenium.
Fundamentals
1. What is Selenium WebDriver and how does it talk to the browser?
WebDriver is an API for controlling a browser the way a user would. Your test code sends commands to a browser driver (ChromeDriver, GeckoDriver, EdgeDriver). The driver is a small server that speaks the W3C WebDriver protocol over HTTP and drives the real browser. That is why driver and browser versions must be compatible. Since Selenium 4.6 the bundled Selenium Manager downloads a matching driver for you automatically.
Likely follow-up: What is the difference between Selenium IDE, WebDriver and Grid? IDE records and replays in the browser, WebDriver is the programming API, Grid runs WebDriver sessions on many machines and browsers in parallel.
2. What locators does Selenium support and which do you prefer?
id, name, className, tagName, linkText, partialLinkText, CSS selector and XPath. Preference order in practice: a stable id or a dedicated test attribute such as data-testid, then a short CSS selector, then XPath only when you need to go up the tree or match by text. Avoid long absolute paths like /html/body/div[2]/div/table/tr[3]/td[1] because any layout change breaks them. Try your selectors in the XPath and CSS tester.
driver.findElement(By.id("email"));
driver.findElement(By.cssSelector("[data-testid='submit']"));
driver.findElement(By.xpath("//label[normalize-space()='Email']/following-sibling::input"));
3. What is the difference between findElement and findElements?
findElement returns the first match and throws NoSuchElementException if there is none. findElements returns a list and an empty list if nothing matches, so it never throws. Use findElements(...).isEmpty() to check that something is absent without try/catch.
4. What is the difference between driver.close() and driver.quit()?
close() closes the current window or tab. quit() ends the session: closes every window and stops the driver process. Always call quit() in teardown, otherwise driver processes pile up on your CI machine.
5. How do you handle dropdowns?
For a real select element use the Select class. For custom dropdowns (a div with a list), click to open it and then click the option like any other element.
Select country = new Select(driver.findElement(By.id("country")));
country.selectByVisibleText("India");
country.selectByValue("IN");
Waits and flakiness
6. Implicit, explicit and fluent waits: what is the difference?
An implicit wait is global: the driver polls for an element for up to N seconds on every lookup. An explicit wait (WebDriverWait) waits for a specific condition on a specific element. A fluent wait is an explicit wait where you also set the polling interval and the exceptions to ignore.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement toast = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".toast")));
Wait<WebDriver> fluent = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
Likely follow-up: Why not mix implicit and explicit waits? The timeouts can add up in unpredictable ways, so a failed explicit wait may take far longer than you set. Pick explicit waits and leave the implicit wait at zero.
7. A test passes locally and fails randomly on CI. How do you investigate?
First, read the failure: what element, what exception. Then check the usual causes in this order: a missing wait (timing), a stale or re-rendered element, test data shared between tests, tests that depend on running in a fixed order, a different screen size on CI (element hidden or overlapped), and environment slowness. Reproduce with the same browser size and headless mode as CI, add a screenshot and page source on failure, and fix the cause. Re-running until green is not a fix.
8. What is StaleElementReferenceException and how do you avoid it?
The element you hold a reference to has been removed from or replaced in the DOM, usually by a re-render after a click or an AJAX update. The reference no longer points to anything. Do not store elements for long: look them up again right before use, or wait for the new element with an explicit wait. See the full fix guide.
9. ElementClickInterceptedException: what causes it?
Another element covers the one you are clicking: a cookie banner, a loader overlay or a sticky header. Wait for the overlay to disappear (invisibilityOfElementLocated), scroll the element into view, or close the banner. A JavaScript click will make the error go away, but it also clicks things a real user could not, so use it only when you understand why it is needed.
Browser features
10. How do you handle alerts, frames and multiple windows?
// Alert
Alert alert = driver.switchTo().alert();
alert.accept();
// iframe: switch in, act, switch back out
driver.switchTo().frame("payment-frame");
driver.findElement(By.id("card")).sendKeys("4111111111111111");
driver.switchTo().defaultContent();
// New window or tab
String original = driver.getWindowHandle();
for (String h : driver.getWindowHandles()) {
if (!h.equals(original)) driver.switchTo().window(h);
}
In Selenium 4 you can also open one directly with driver.switchTo().newWindow(WindowType.TAB).
11. How do you upload a file?
If the page has an input type="file", send the file path to it with sendKeys. Do not try to drive the operating system's file dialog.
driver.findElement(By.cssSelector("input[type='file']"))
.sendKeys("/absolute/path/to/resume.pdf");
12. How do you perform mouse hover, drag and drop or keyboard shortcuts?
Use the Actions class.
Actions actions = new Actions(driver);
actions.moveToElement(menu).perform();
actions.dragAndDrop(source, target).perform();
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
13. What is new in Selenium 4 that you have used?
Relative locators (RelativeLocator.with(By.tagName("input")).below(By.id("email"))), newWindow for tabs and windows, element screenshots, Selenium Manager for automatic driver management, and the BiDi/DevTools APIs for things like network interception and console logs. Mention only what you have actually used.
Framework design
14. Explain the Page Object Model.
Each page (or component) gets a class that holds its locators and exposes actions in business terms (loginPage.loginAs(user)), and the tests only call those methods. When the UI changes you fix one class instead of fifty tests. Keep assertions in the tests, not the page objects.
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);
}
}
Likely follow-up: What is PageFactory and do you use it? It initialises @FindBy fields lazily. Many teams skip it today in favour of plain By fields because it hides timing problems and is harder to debug.
15. How do you run tests in parallel safely?
Each thread needs its own WebDriver. Keep the driver in a ThreadLocal<WebDriver> (or let your test framework create one per test), never in a static field shared by threads. Make tests independent: no shared logins that get logged out, no dependence on another test's data. Then configure parallelism in TestNG (parallel="methods") or JUnit 5.
16. What do you do on test failure?
Take a screenshot and save the page source and browser console logs, attach them to the report, and quit the driver in a finally or @AfterMethod so the browser never leaks.
File shot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(shot.toPath(), Path.of("target/screenshots/" + testName + ".png"));
17. What are the limitations of Selenium?
It only automates browsers (no desktop apps, no native mobile on its own: that is Appium's role), it has no built-in reporting or test runner, it cannot read captchas or QR codes, and its tests are slower and more fragile than API tests. A sensible test pyramid keeps most checks at API or unit level and uses Selenium for a few important user journeys.
18. Selenium or Playwright for a new project?
Both are good. Selenium has the widest language and browser support and a huge installed base in Indian companies, so it is on most job descriptions. Playwright has auto-waiting, tracing and a faster setup built in. Read Selenium vs Playwright for the details, and be ready to say which you would pick and why.
Real-world automation problems
19. How do you handle elements whose ids or classes change on every load?
Do not lean on the changing part. Look for something stable: a data-testid or other test attribute (ask the developers to add one, it is a small change), a label, a role, the visible text, or a stable parent with a relative path. When part of an attribute is stable, use starts-with(@id,'order-') in XPath or [id^='order-'] in CSS. Dynamic ids are a good reason to agree test attributes with the team early.
20. What is JavascriptExecutor and when would you use it?
It runs JavaScript in the page from your test. Useful for scrolling an element into view, reading values the DOM exposes only through script, or clicking an element that is truly there but awkward. Treat it as a last resort: a JavaScript click skips the checks a real click makes (is it visible, is something covering it), so it can hide real bugs.
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView({block:'center'});", element);
21. How does Selenium Grid work, and what changed in Selenium 4?
Grid lets tests run on many machines and browsers in parallel. Your test asks the Grid for a session with certain capabilities (browser, version, platform); the Grid routes it to a node that can provide it. Selenium 4 rebuilt Grid into separate components (router, distributor, session map, event bus, nodes) that can run on one machine or be spread out, and added a web UI and observability. Cloud providers offer the same idea as a service.
22. Why can a test pass in headed mode and fail headless?
Headless browsers can have a different default window size, so a responsive layout shows different elements. They may differ in fonts, GPU behaviour, download handling and pop-ups. Set the window size explicitly, use the same browser mode locally and in CI, and take a screenshot on failure to see what the headless browser saw.
23. How can you skip the login form in most tests?
Log in once through the API, take the session cookie or token, add it to the browser, and open the page. The login itself still gets its own UI tests. This makes the suite much faster and removes the most common source of failure.
driver.get(baseUrl); // cookies need a page on the same domain
driver.manage().addCookie(new Cookie("session", token));
driver.navigate().refresh();
24. How do you handle a browser authentication pop-up (HTTP basic auth)?
The pop-up is not part of the page, so locators cannot reach it. Common options: put the credentials in the URL (https://user:pass@host/ works in some browsers, not all), use the browser's DevTools protocol through Selenium 4 to send an authorization header, or authenticate at the network level in your test environment. Name the limitation when you answer: it differs by browser.
25. How do you check for broken links on a page?
Collect every a element's href, then request each URL with an HTTP client (not the browser) and check the status code. Skip mailto: and javascript: links, and de-duplicate. Do it in parallel and with a timeout.
HttpClient client = HttpClient.newHttpClient();
for (String url : urls) {
HttpResponse<Void> r = client.send(HttpRequest.newBuilder(URI.create(url)).method("HEAD", HttpRequest.BodyPublishers.noBody()).build(),
HttpResponse.BodyHandlers.discarding());
if (r.statusCode() >= 400) System.out.println(url + " -> " + r.statusCode());
}
Some servers refuse HEAD; retry those with GET.
26. What is the difference between a hard assert and a soft assert?
A hard assert (Assert.assertEquals) stops the test at the first failure. A soft assert (TestNG's SoftAssert) records failures and carries on, then reports them all when you call assertAll(). Use soft asserts when checking many independent things on one page (every field of a form), and hard asserts when later steps make no sense after a failure.
SoftAssert soft = new SoftAssert();
soft.assertEquals(title.getText(), "Dashboard");
soft.assertTrue(logout.isDisplayed());
soft.assertAll(); // forgetting this line is the classic mistake
27. Which TestNG features do you use in a framework?
Annotations for set-up and tear-down at suite, class and method level; @DataProvider for data-driven tests; groups to run smoke or regression sets; priority and dependsOnMethods (sparingly: dependent tests make failures confusing); listeners (ITestListener) to take a screenshot on failure; retryAnalyzer (careful: it can hide flaky tests); and the XML suite file or Maven Surefire to run in parallel.
28. How do you handle shadow DOM in Selenium?
Get the shadow root of the host element, then search inside it with CSS selectors. XPath does not work inside a shadow root.
SearchContext root = driver.findElement(By.cssSelector("my-widget")).getShadowRoot();
root.findElement(By.cssSelector("button.save")).click();
A closed shadow root cannot be reached from outside; ask for a test hook. You can try this on the shadow DOM playground page.
29. How do you set browser options, such as a download folder or disabling notifications?
Through the options class for the browser, passed to the driver when you create it.
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications", "--window-size=1366,768");
options.setExperimentalOption("prefs", Map.of("download.default_directory", downloadDir.toString()));
WebDriver driver = new ChromeDriver(options);
Keep the options in one factory class so every test gets the same browser configuration.
30. What are the page load strategy and the timeouts in Selenium?
pageLoadStrategy decides when get() returns: normal waits for the load event, eager returns once the DOM is ready, none returns at once. The timeouts are separate: pageLoadTimeout (how long a page may take), scriptTimeout (for async scripts) and the implicit wait. A single page-heavy app often does better with eager plus explicit waits for the elements you need.
31. How do you make a slow Selenium suite faster?
First measure which tests are slow. Then: run in parallel with independent tests; log in through the API; create test data through the API instead of the UI; replace fixed sleeps with condition waits; move checks that do not need a browser down to API level; run a small smoke set on every push and the full suite nightly; and start from a clean, fast environment (containers). Cutting waits and logins usually gives the biggest gain.
32. How do you deal with a test that needs a file download?
Set the download directory in the browser options, trigger the download, then wait for the file to appear in that folder (poll with a timeout, ignoring partial files such as .crdownload) and check its name and content. Do not drive the operating system's save dialog.
Practise it
Try each of these on the practice playground: handle the alert, switch into the iframe, upload a file, and wait for the dynamic content to load without using Thread.sleep.
Want a project you can show in interviews?
The portfolio project kit walks you through testing a deliberately buggy app with Selenium or Playwright and API tests, then explaining it. The app itself is free.
