Interview Questions

Top 60 Selenium Interview Questions & Answers (2026 Guide)

60 Selenium interview questions with clear answers and Java code — WebDriver basics, locators, waits, exceptions, Page Object Model, TestNG, Grid and real interview scenarios.

✍️ By QA Jobs India📅 14 Oct 2026⏱ 15 min read

Selenium is still one of the most requested skills in QA automation job descriptions in India, especially in Java-based teams. Whether you are a fresher moving from manual testing or an experienced SDET, interviewers keep coming back to the same core areas: locators, waits, exceptions and framework design.

This guide covers 60 Selenium interview questions in seven groups — basics, locators, waits, handling web elements, exceptions, framework design and real-world scenarios — with short Java snippets you can explain confidently. All examples use Selenium 4.

Key takeaways

  • Locators and waits come up in almost every Selenium round — know when to use CSS vs XPath and explicit vs implicit waits.
  • Be ready to explain your framework end to end: POM, TestNG, data, reporting and CI.
  • Know the common exceptions (stale element, click intercepted) and how you fixed them in a real project.
  • Selenium 4 features — Selenium Manager, relative locators, new window API and Grid 4 — show that your knowledge is current.

Selenium basics (1–10)

1. What is Selenium?
Selenium is a free, open-source suite for automating web browsers. It follows the W3C WebDriver standard and supports Java, Python, C#, JavaScript and Ruby, so the same test idea can run on Chrome, Firefox, Edge and Safari.

2. What are the components of Selenium?
Selenium WebDriver (the browser-automation API used in frameworks), Selenium IDE (a record-and-playback browser extension for quick scripts) and Selenium Grid (runs tests on many browsers and machines in parallel).

3. How does Selenium WebDriver work?
Your test code calls the language bindings, which send W3C WebDriver commands over HTTP to a browser driver such as chromedriver or geckodriver. The driver controls the real browser and returns the result. Selenium 4 also supports the newer WebDriver BiDi protocol for two-way communication like listening to console logs and network events.

4. What is new in Selenium 4?
Full W3C WebDriver compliance, relative locators, the new window/tab API, element-level screenshots, Chrome DevTools and BiDi access, a rewritten Grid 4, browser Options classes in place of DesiredCapabilities, and Selenium Manager for automatic driver setup.

5. What is Selenium Manager?
A tool built into Selenium (from version 4.6) that detects the installed browser and downloads the matching driver automatically. You no longer need System.setProperty() or a separate WebDriverManager library in most projects.

6. What are the advantages and limitations of Selenium?
Advantages: free, multi-language, multi-browser, huge community and easy CI integration. Limitations: web apps only (use Appium for mobile), no built-in reporting or test runner, CAPTCHA cannot be automated by design, and visual or image checks need extra tools.

7. What is the difference between driver.get() and driver.navigate().to()?
Both open a URL and wait for the page to load. navigate() also gives back(), forward() and refresh(), so it is used when a test needs browser-history actions.

8. What is the difference between close() and quit()?
close() closes only the current window. quit() closes every window and ends the WebDriver session and driver process. Always call quit() in teardown, otherwise driver processes pile up on the CI machine.

9. What is the difference between findElement() and findElements()?
findElement() returns the first match or throws NoSuchElementException. findElements() returns a list, which is empty when nothing matches — handy for checking whether an element is present without catching an exception.

10. How do you run Selenium tests in headless mode?
Headless mode runs the browser without a visible window, which is faster and ideal for CI servers. Pass the headless argument through the browser options:

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
WebDriver driver = new ChromeDriver(options);

Locators (11–20)

11. Which locators does Selenium support?
id, name, className, tagName, linkText, partialLinkText, cssSelector and xpath, plus the relative locators added in Selenium 4.

12. Which locator should you prefer and why?
Use a unique, stable attribute first: id, name or a dedicated test attribute such as data-testid. Then prefer CSS, and use XPath when you need text matching or to move up the DOM. Avoid auto-generated IDs and index-based locators — they break on every UI change.

13. What is the difference between absolute and relative XPath?
Absolute XPath starts from the root (/html/body/div[2]/form/input) and breaks with any layout change. Relative XPath starts anywhere with // and an attribute (//input[@name='email']), so it is far more stable.

14. How do you handle dynamic elements whose IDs change?
Match the stable part of the attribute with contains() or starts-with(), match visible text, or anchor on a stable nearby element:

//input[starts-with(@id,'user_')]
//button[contains(@class,'btn-submit')]
//a[normalize-space()='Apply Now']

15. What are XPath axes? Give an example.
Axes move relative to a known node: parent, child, ancestor, descendant, following-sibling and preceding-sibling. They are useful when the target has no good attributes but its label does:

//label[text()='Email']/following-sibling::input
//td[text()='Rahul']/parent::tr//button[text()='Edit']

16. CSS selector vs XPath — which is better?
CSS is shorter, readable and widely supported. XPath can match visible text and move to parent or ancestor nodes, which CSS cannot. A good answer: use CSS by default, XPath when you need text or upward traversal.

17. What are relative locators in Selenium 4?
They find an element by its position relative to another: above(), below(), toLeftOf(), toRightOf() and near().

WebElement password = driver.findElement(
    RelativeLocator.with(By.tagName("input")).below(By.id("email")));

18. What is the difference between getText() and getAttribute()?
getText() returns the visible inner text of an element. To read what is typed in an input box, use getAttribute("value"). Selenium 4 also adds getDomAttribute() (the attribute as written in HTML) and getDomProperty() (the live JavaScript property).

19. What do isDisplayed(), isEnabled() and isSelected() check?
isDisplayed() — element is visible on the page; isEnabled() — it can be interacted with (not disabled); isSelected() — a checkbox, radio button or option is selected.

20. How do you find elements inside a Shadow DOM?
In Selenium 4, get the shadow host, call getShadowRoot(), then search inside it with a CSS selector (XPath is not supported inside a shadow root).

WebElement host = driver.findElement(By.cssSelector("user-card"));
SearchContext shadow = host.getShadowRoot();
shadow.findElement(By.cssSelector("button.follow")).click();

Waits and synchronisation (21–27)

21. Why do we need waits in Selenium?
Modern pages load content with JavaScript and AJAX, so an element may not exist or be clickable the moment the script looks for it. Waits synchronise the test with the application and prevent flaky NoSuchElementException failures.

22. What is an implicit wait?
A global setting that makes every findElement() keep polling for up to the given time before failing.

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

23. What is an explicit wait?
A wait for one specific condition on one element, using WebDriverWait and ExpectedConditions. This is the recommended approach.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement btn = wait.until(
    ExpectedConditions.elementToBeClickable(By.id("submit")));
btn.click();

24. What is a FluentWait?
An explicit wait where you also set the polling interval and the exceptions to ignore while waiting.

Wait<WebDriver> wait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(20))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class);
WebElement msg = wait.until(d -> d.findElement(By.id("toast")));

25. Why should you avoid Thread.sleep()?
It always waits the full time even when the element is ready, which slows the whole suite, and it still fails when the app is slower than the fixed delay. Explicit waits finish as soon as the condition is met.

26. Can you mix implicit and explicit waits?
The Selenium documentation advises against it, because combining them can produce unpredictable wait times. Keep the implicit wait at zero and use explicit waits everywhere.

27. What are page load timeout and page load strategy?
pageLoadTimeout() sets how long to wait for a page to load before throwing TimeoutException. The page load strategy decides when get() returns: normal (full load, the default), eager (DOM ready) or none.

Handling web elements (28–40)

28. How do you handle dropdowns?
For a standard <select> element, use the Select class. Custom dropdowns built with div or li are handled by clicking to open and then clicking the option.

Select city = new Select(driver.findElement(By.id("city")));
city.selectByVisibleText("Pune");
city.selectByValue("BLR");
city.selectByIndex(2);

29. How do you handle JavaScript alerts?
Switch to the alert, then accept, dismiss, read its text or type into a prompt. Wait for it first with ExpectedConditions.alertIsPresent().

Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String text = alert.getText();
alert.accept();   // or alert.dismiss();

30. How do you work with iframes?
Switch into the frame by index, name/ID or WebElement, perform actions, then come back with switchTo().defaultContent() (or parentFrame() for nested frames). frameToBeAvailableAndSwitchToIt waits and switches in one step.

31. How do you handle multiple windows or tabs?
Store the parent handle, loop through getWindowHandles() and switch to the new one. Selenium 4 can also open a new tab or window directly.

String parent = driver.getWindowHandle();
for (String h : driver.getWindowHandles()) {
    if (!h.equals(parent)) driver.switchTo().window(h);
}
// Selenium 4
driver.switchTo().newWindow(WindowType.TAB);

32. How do you perform mouse hover, drag-and-drop, right-click and double-click?
Use the Actions class and finish the chain with perform().

Actions act = new Actions(driver);
act.moveToElement(menu).perform();
act.dragAndDrop(source, target).perform();
act.contextClick(element).perform();
act.doubleClick(element).perform();

33. How do you perform keyboard actions?
Send Keys to an element (sendKeys(Keys.ENTER)) or build combinations with Actions, for example keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL) to select all.

34. When do you use JavascriptExecutor?
To scroll, read page state, or as a last resort to click an element that a normal click cannot reach. Use it carefully — it bypasses real user behaviour and can hide genuine UI bugs.

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView({block:'center'});", element);
js.executeScript("arguments[0].click();", element);

35. How do you scroll a page?
Use scrollIntoView or window.scrollBy(0, 500) through JavascriptExecutor, or in newer Selenium 4 versions the Actions method scrollToElement(element).

36. How do you upload a file?
Call sendKeys() with the absolute file path on the <input type="file"> element — no OS dialog needed. When running on Selenium Grid, set a LocalFileDetector on the RemoteWebDriver so the file is sent to the remote node.

driver.findElement(By.cssSelector("input[type='file']"))
      .sendKeys("C:\\data\\resume.pdf");

37. How do you verify a file download?
Set the browser’s download folder through options (for Chrome, the download.default_directory preference), trigger the download, then wait until the file appears in that folder and check its name and size.

38. How do you take a screenshot?
Cast the driver to TakesScreenshot. Selenium 4 can also capture a single element. In frameworks, screenshots are usually taken automatically on failure through a TestNG listener.

File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(src.toPath(), Paths.get("screenshots/home.png"));
// element screenshot (Selenium 4)
File logo = driver.findElement(By.id("logo")).getScreenshotAs(OutputType.FILE);

39. How do you handle SSL certificate errors?
Tell the browser to accept insecure certificates through options: options.setAcceptInsecureCerts(true); — useful for test environments with self-signed certificates.

40. How do you handle a basic authentication popup?
Pass the credentials in the URL (https://user:pass@site.com), or in Chromium browsers use Selenium 4’s HasAuthentication interface to register the username and password before opening the page.

Common exceptions (41–45)

41. Name some common Selenium exceptions.
NoSuchElementException, StaleElementReferenceException, ElementNotInteractableException, ElementClickInterceptedException, TimeoutException, NoSuchFrameException, NoSuchWindowException, NoAlertPresentException, InvalidSelectorException and SessionNotCreatedException.

42. What causes StaleElementReferenceException and how do you fix it?
The element you stored was removed or re-rendered in the DOM (after a refresh, AJAX update or navigation). Fix it by locating the element again just before using it, waiting for the page to settle, and not caching WebElements for long. ExpectedConditions.refreshed() helps in some cases.

43. How do you fix ElementClickInterceptedException?
Another element — a loader, overlay, cookie banner or sticky header — is covering the target. Wait for the overlay to disappear (invisibilityOfElementLocated), scroll the element to the centre, close the banner, and use a JavaScript click only as the last option.

44. What is ElementNotInteractableException?
The element exists in the DOM but cannot be used — it is hidden, has zero size or is disabled. Wait for elementToBeClickable, and check that your locator is not matching a hidden duplicate (common with mobile and desktop menus on the same page).

45. What causes SessionNotCreatedException?
Usually a mismatch between the browser and driver versions, or invalid browser options. Updating Selenium so that Selenium Manager fetches the right driver normally solves it.

Framework design (46–55)

46. What is the Page Object Model (POM)?
A design pattern where each page has its own class holding its locators and actions. Tests call page methods instead of raw Selenium code, so a UI change is fixed in one place and tests read like business steps.

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

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

    public void login(String user, String pass) {
        driver.findElement(email).sendKeys(user);
        driver.findElement(password).sendKeys(pass);
        driver.findElement(loginBtn).click();
    }
}

47. What is Page Factory and how is it different from POM?
Page Factory is a helper for POM that uses @FindBy annotations and PageFactory.initElements() to create lazy element proxies. POM is the pattern; Page Factory is one way to implement it. Many teams now prefer plain By locators in POM because they are simpler and avoid stale proxy issues on dynamic pages.

48. What is the execution order of TestNG annotations?
@BeforeSuite → @BeforeTest → @BeforeClass → @BeforeMethod → @Test → @AfterMethod → @AfterClass → @AfterTest → @AfterSuite.

49. How do you implement data-driven testing?
Use TestNG’s @DataProvider to feed multiple data sets into one test, reading data from Excel (Apache POI), CSV or JSON files when needed.

@DataProvider(name = "logins")
public Object[][] logins() {
    return new Object[][] {
        {"valid@test.com", "Pass@123", true},
        {"wrong@test.com", "bad", false}
    };
}

@Test(dataProvider = "logins")
public void loginTest(String user, String pass, boolean ok) { ... }

50. What is the difference between hard assert and soft assert?
A hard assert (Assert.assertEquals) stops the test at the first failure. A soft assert (SoftAssert) records failures and continues; you must call assertAll() at the end to report them.

51. How do you re-run failed tests?
Run the auto-generated testng-failed.xml, or implement IRetryAnalyzer to retry a failed test a limited number of times. Mention that retries are a safety net — the real fix is removing the cause of flakiness.

52. How do you run tests in parallel?
Set parallel (methods, classes or tests) and thread-count in testng.xml, and keep one driver per thread with ThreadLocal so tests do not share a browser. Use Selenium Grid to scale across machines.

private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();

public static WebDriver getDriver() { return driver.get(); }
public static void setDriver(WebDriver d) { driver.set(d); }

53. What is Selenium Grid 4 and how is it structured?
Grid runs tests on remote browsers in parallel. Grid 4 is made of a Router, Distributor, Session Map, New Session Queue, Event Bus and Nodes, and can run as Standalone, Hub-and-Node, or fully Distributed — often with the official Docker images. Tests connect through RemoteWebDriver.

WebDriver driver = new RemoteWebDriver(
    new URL("http://localhost:4444"), new ChromeOptions());

54. Explain the automation framework you worked on.
Interviewers ask this in almost every automation round. A typical answer covers: Java + Maven, TestNG or JUnit, Page Object Model, a config file for URLs and browsers, utilities for waits and screenshots, test data in Excel/JSON, reporting with Extent Reports or Allure, Log4j2 logging, Git, and CI with Jenkins or GitHub Actions. Describe your project honestly and mention one problem you solved.

55. How do you run Selenium tests in CI/CD?
Trigger the Maven command (for example mvn test with a suite file) from Jenkins or GitHub Actions on every pull request or nightly, run browsers headless or on a Dockerised Grid, and publish the HTML report and failure screenshots as build artifacts.

Scenario-based questions (56–60)

56. How do you find broken links on a page?
Collect all a tags, read each href, send an HTTP request, and treat a status code of 400 or above as broken.

for (WebElement a : driver.findElements(By.tagName("a"))) {
    String url = a.getAttribute("href");
    if (url == null || !url.startsWith("http")) continue;
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.setRequestMethod("HEAD");
    if (con.getResponseCode() >= 400) System.out.println("Broken: " + url);
}

57. How do you handle CAPTCHA and OTP in automation?
CAPTCHA is designed to stop bots, so it should not be automated. Ask developers to disable it or use test keys in the QA environment. For OTP, read it from an API, database or test mailbox, or use a fixed OTP configured for the test environment.

58. How do you reduce flaky tests?
Use explicit waits instead of sleeps, stable locators, independent tests with their own data, a fresh browser session per test, and clean test environments. Track flaky tests separately and fix the root cause rather than relying on retries.

59. How do you read values from a dynamic web table?
Locate the rows, loop through them and read the cells, or jump straight to a row using XPath on its text.

List<WebElement> rows = driver.findElements(By.xpath("//table[@id='jobs']/tbody/tr"));
for (WebElement row : rows) {
    String company = row.findElement(By.xpath("./td[2]")).getText();
}
// direct: //td[text()='Infosys']/following-sibling::td[1]

60. Selenium vs Playwright vs Cypress — which would you choose?
Selenium supports many languages and every major browser through the W3C standard and has the largest ecosystem. Playwright offers built-in auto-waiting, tracing and fast parallel runs. Cypress is JavaScript-only and runs inside the browser. A balanced answer: Selenium remains common in large and services companies, many new projects choose Playwright, and knowing both makes you a stronger candidate.

How to answer Selenium questions in an interview

Interviewers care more about how you solved real problems than about textbook definitions. For every concept, add one line from your project — “we had flaky tests because of a loading spinner, so I added an explicit wait for its invisibility”. Expect a live coding task such as automating a login, a dropdown or a web table, plus core Java questions on strings, collections and OOP. The official Selenium documentation is worth a read before your interview. Most automation rounds also include manual, API and SQL questions, so revise our manual testing interview questions, API testing interview questions and SQL interview questions for testers, or browse the full QA interview questions bank.

🚀 Looking for Selenium automation jobs?

QA Jobs India shares 100+ fresh QA & software testing openings every morning — Selenium, automation, API, manual and remote roles with direct HR emails.

See today’s QA jobs →

FAQs

Is Selenium still in demand in 2026?

Yes. Selenium with Java remains common in QA automation roles in India, especially in large product and services companies. Playwright is growing fast, so knowing Selenium first and then Playwright makes your profile stronger.

Which programming language should I learn with Selenium?

Java is the most common in Indian job descriptions, followed by Python. Pick one and learn its basics well — strings, collections, OOP and exception handling — because coding questions are asked along with Selenium.

What Selenium questions are asked to freshers?

Freshers usually get basics, locators, waits, handling dropdowns, alerts, frames and windows, plus the idea of Page Object Model and TestNG annotations.

How do I prepare for a Selenium coding round?

Practise small scripts on demo sites: login, dropdown, multiple windows, iframes, a web table and broken links. Write them using Page Object Model and explicit waits, and explain each step aloud.

Conclusion

These 60 Selenium interview questions cover what Indian companies ask most — from WebDriver basics and locators to waits, exceptions, POM, TestNG and Grid. Practise the code snippets, connect each answer to your own project, and you will walk into your automation interview with confidence. When you are ready to apply, check the daily QA jobs list for fresh Selenium openings.

💎 Get every QA opening, every day

Join QA Jobs India Premium for 100+ verified QA jobs daily with HR contact details.

✓ You're subscribed — job alerts arrive daily at 9 AM
Scroll to Top