Selenium Engineer Interview: Coding Round Tasks (2027)

36 Selenium coding round tasks with Java and Python answers: setup, locators, waits, frames, uploads, page objects, data-driven tests and Grid.

Sep 27, 2025 - 17:23
Nov 11, 2026 - 06:08
 0  55
Selenium Engineer Interview: Coding Round Tasks (2027)

A Selenium engineer interview usually ends with a coding round: you open an IDE, start a browser, find elements, wait correctly, handle a frame or a new window, and wrap it all in a small page object framework. This page lists 36 of those tasks with short answers and Java or Python code, grouped by what the interviewer checks.

The code was checked against the Selenium documentation in November 2026, when the current release was Selenium 4.52.0. For concept questions (what is WebDriver, what is Grid) read our 100+ Selenium interview questions guide first. This page is about writing and fixing code under time pressure.

Key takeaways

  • Coding rounds reward small, correct, readable code. A test that waits on a condition and asserts one thing beats a long script full of sleeps.
  • The same eight areas come up again and again: setup, locators, waits, windows and frames, forms and uploads, page objects, data-driven tests and Grid.
  • Selenium Manager downloads and selects the browser driver for you in current releases, so you rarely set a driver path by hand.
  • Do not mix implicit and explicit waits. The Selenium documentation says this can cause unpredictable wait times.
  • Page objects should not hold assertions. Keep assertions in the test and let the page object expose actions and state.
  • Say what you would check next when a task is ambiguous. Interviewers often score that reasoning more than the final line of code.

What a Selenium coding round usually checks

Task typeWhat the interviewer wants to seeQuestions below
Start and stop a browserClean setup, quit in a finally block or teardown, headless option1 to 5
Find elementsStable locators, no brittle absolute XPath6 to 12
SynchroniseExplicit waits, no sleeps13 to 17
Windows, frames, alertsSwitching context and switching back18 to 22
Forms, uploads, mouse actionsThe right API for each control23 to 27
Framework structurePage objects, base test, data-driven tests, failure screenshots28 to 33
Grid and parallel runsRemote sessions, one driver per thread34 to 36

Setup tasks (questions 1 to 5)

1. Write the smallest test that opens a page and checks the title.

Start the driver, open the page, assert, and always quit.

WebDriver driver = new ChromeDriver();
try {
    driver.get("https://www.selenium.dev/selenium/web/web-form.html");
    assertEquals("Web form", driver.getTitle());
} finally {
    driver.quit();
}

The finally block matters. Without it a failed assertion leaves a browser process running, and a long suite slowly fills the machine.

2. Do you need to download chromedriver first?

No, not in current releases. Selenium Manager is a command line tool written in Rust that ships with the Selenium bindings. It finds or downloads the matching driver and, when needed, the browser. You only set a driver path yourself on locked-down machines that cannot reach the internet.

3. Start Chrome in headless mode.

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

Headless suits CI machines without a display. If a test passes headed and fails headless, check the window size first, because a different viewport can hide or move elements. Set the size explicitly in the options so both modes match.

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

close() closes the current window or tab. quit() ends the whole session and closes every window the driver opened. Use quit() in teardown. Use close() only when you opened a second window and want to return to the first.

5. Write the same start-up in Python.

from selenium import webdriver

driver = webdriver.Chrome()
try:
    driver.get("https://www.selenium.dev/selenium/web/web-form.html")
    assert driver.title == "Web form"
finally:
    driver.quit()

Locator tasks (questions 6 to 12)

6. Which locator strategies does WebDriver support?

Eight: id, name, class name, tag name, link text, partial link text, CSS selector and XPath. Prefer an id when the page has a unique one, then a CSS selector. Use XPath when you need to move up to a parent or match on text.

7. Click a button that has no id.

driver.findElement(By.cssSelector("form#login button[type='submit']")).click();

Anchor on something stable, such as the form id and the button type, rather than a long path of div elements. Say out loud that you would ask the developers for a data-testid attribute if the page offers nothing stable.

8. Why is an absolute XPath such as /html/body/div[2]/div[1]/button a poor locator?

It breaks when anyone adds a wrapper div, because it encodes the whole page structure. A short relative locator such as //button[normalize-space()='Pay now'] or a CSS selector tied to an attribute survives layout changes.

9. The element id changes on every page load. What do you do?

Locate by a part of the id that stays fixed, or by another attribute.

driver.findElement(By.cssSelector("input[id^='user_']"));   // starts with
driver.findElement(By.cssSelector("input[id$='_email']"));  // ends with

10. Find every link in a table column and print the text.

List<WebElement> links = driver.findElements(By.cssSelector("table#orders td:nth-child(2) a"));
for (WebElement link : links) {
    System.out.println(link.getText());
}

findElements returns an empty list when nothing matches. findElement throws NoSuchElementException. Use the plural form when "zero results" is a valid outcome.

11. What are relative locators in Selenium 4?

They find an element by its position relative to another one: above, below, toLeftOf, toRightOf and near.

WebElement password = driver.findElement(By.id("password"));
WebElement label = driver.findElement(RelativeLocator.with(By.tagName("label")).above(password));

They help with forms where the label has no useful attribute. Do not use them as a first choice, because a layout change moves the elements.

12. An element sits inside a shadow DOM. How do you reach it?

Get the host element, then ask for its shadow root, then search inside it.

WebElement host = driver.findElement(By.cssSelector("#settings-panel"));
SearchContext shadow = host.getShadowRoot();
shadow.findElement(By.cssSelector("button.save")).click();

Search from the shadow root with a CSS selector. If a locator that worked on the normal page fails there, the shadow boundary is the first thing to suspect.

Waiting tasks (questions 13 to 17)

13. Click a button that appears two seconds after a click elsewhere.

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

The wait polls until the condition is true or ten seconds pass, then throws TimeoutException. It returns as soon as the button is ready, so a fast page costs no extra time.

14. Same task in Python.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

pay = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "pay")))
pay.click()

15. Why not use Thread.sleep(5000)?

It always waits the full five seconds, even when the page is ready in 300 ms, and it still fails when the page needs six. A suite with hundreds of sleeps becomes slow and flaky at the same time.

16. What is the default implicit wait, and should you use it?

The default is zero, so a missing element fails immediately. Many teams set one global implicit wait and nothing else. The risk is mixing it with explicit waits, which Selenium warns can produce unpredictable timing. Pick explicit waits and leave the implicit wait at zero.

17. When would you use FluentWait?

When you need control over the polling interval or which exceptions to ignore.

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

WebDriverWait is a ready-made FluentWait for the common case, so reach for the longer form only when you need those extra settings.

Windows, frames and alerts (questions 18 to 22)

18. A link opens a new tab. Switch to it, read the heading, and come back.

String original = driver.getWindowHandle();
driver.findElement(By.linkText("Open report")).click();
new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
    if (!handle.equals(original)) {
        driver.switchTo().window(handle);
    }
}
String heading = driver.findElement(By.tagName("h1")).getText();
driver.close();
driver.switchTo().window(original);

Wait for the second window before reading the handles, otherwise the loop runs too early. After close() you must switch back, or the driver keeps pointing at the closed window and throws NoSuchWindowException.

19. Open a new tab yourself.

driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://example.com");

Selenium 4 creates the tab and switches to it in one call.

20. A button inside an iframe cannot be found. Why?

Selenium only sees the top-level document until you switch into the frame. Switch by id, name, index or the frame element, then switch back out.

driver.switchTo().frame("buttonframe");
driver.findElement(By.tagName("button")).click();
driver.switchTo().defaultContent();

21. Accept a JavaScript confirm dialog and read its text.

driver.findElement(By.id("confirm")).click();
Alert alert = new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.alertIsPresent());
String text = alert.getText();
alert.accept();

Use dismiss() to cancel and sendKeys() for a prompt. These calls work only for native browser dialogs, not for a modal built from HTML. A styled modal is ordinary page content and you locate it like any other element.

22. What exception do you get after a page refresh when you reuse an element?

StaleElementReferenceException. The reference points at a node that no longer exists in the page. Find the element again after the refresh, or write a small helper that re-locates and retries once.

Forms, uploads and mouse actions (questions 23 to 27)

23. Choose a value in a select dropdown.

Select country = new Select(driver.findElement(By.id("country")));
country.selectByVisibleText("India");

The Select class works only for real HTML select and option elements. A dropdown built from div or li elements is clicked like any other element.

24. Upload a file.

driver.findElement(By.cssSelector("input[type='file']")).sendKeys("/home/ci/data/invoice.pdf");

Send the path straight to the file input. Do not click the button and try to drive the operating system dialog, because Selenium cannot control it.

25. Hover over a menu and click a sub item.

Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.id("products"))).perform();
new WebDriverWait(driver, Duration.ofSeconds(5))
    .until(ExpectedConditions.elementToBeClickable(By.linkText("Reports"))).click();

26. A normal click throws ElementClickInterceptedException. What now?

Something else covers the element, often a cookie banner, a sticky header or a loading overlay. First wait for the overlay to disappear or close the banner. Scrolling the element into view often fixes a sticky header. A JavaScript click should be the last resort, because it bypasses the checks a real user faces and can hide a genuine bug.

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

27. Take a screenshot.

File shot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(shot.toPath(), Path.of("target/failure-login.png"), StandardCopyOption.REPLACE_EXISTING);

Framework tasks (questions 28 to 33)

28. Write a page object for a login page.

public class LoginPage {
    private final WebDriver driver;
    private final By username = By.id("username");
    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(username).sendKeys(user);
        driver.findElement(password).sendKeys(pass);
        driver.findElement(submit).click();
        return new DashboardPage(driver);
    }
}

The method returns the next page object, so the test reads like the user journey and a change in the flow shows up as a compile error.

29. Where do assertions go?

In the test. The Selenium documentation says page objects should not make verifications or assertions, with the one exception of a check in the constructor that the right page loaded. The page object exposes values, such as getWelcomeText(), and the test decides whether they are correct.

30. Write a base test with setup and teardown.

public abstract class BaseTest {
    protected WebDriver driver;

    @BeforeEach
    void start() { driver = new ChromeDriver(); }

    @AfterEach
    void stop() { if (driver != null) driver.quit(); }
}

31. Run the same login test with three sets of data.

@ParameterizedTest
@CsvSource({"alice,Secret1,Dashboard", "bob,Secret2,Dashboard", "guest,wrong,Login"})
void loginShowsExpectedPage(String user, String pass, String expectedTitle) {
    new LoginPage(driver).loginAs(user, pass);
    assertEquals(expectedTitle, driver.getTitle());
}

In TestNG the same idea is a @DataProvider. Keep test data outside the test class once it grows, in a CSV or JSON file.

32. Capture a screenshot automatically when a test fails.

With JUnit 5, write a TestWatcher extension that receives the failed test and calls the screenshot code from question 27. With TestNG, use an ITestListener and the onTestFailure method. Name the file after the test so the CI artifact is easy to read.

33. How do you stop a flaky test from hiding a real bug?

Find the cause before adding a retry. Typical causes are a missing wait, shared test data, or a test that depends on another test's result. A retry rule can stay as a safety net, but report the retried tests separately so the number does not disappear.

Grid and parallel tasks (questions 34 to 36)

34. Start a Grid on one machine and run a test against it.

java -jar selenium-server-4.52.0.jar standalone
ChromeOptions options = new ChromeOptions();
WebDriver driver = new RemoteWebDriver(new URI("http://localhost:4444").toURL(), options);

Standalone mode runs all Grid components in one process and listens on port 4444 by default. For several machines the documentation describes Hub and Node mode, started with java -jar selenium-server-<version>.jar hub and ... node.

35. Why must each parallel test have its own driver?

A WebDriver instance holds one browser session and is not safe to share between threads. Two tests clicking in the same browser corrupt each other. The usual pattern is a ThreadLocal<WebDriver> that each test thread fills in setup and clears in teardown.

private static final ThreadLocal<WebDriver> DRIVER = new ThreadLocal<>();

36. Tests pass locally and fail on the CI machine. What do you check?

Work from the cheapest check to the dearest. Compare browser and driver versions, then the window size, then timing (CI machines are often slower), then test data and environment URLs. Download the failure screenshot and the browser log before changing code. Keep the answer in that order and the interviewer will see a method rather than a guess.

How to practise before the interview

  1. Pick a public practice page such as the Selenium web form page and write questions 1, 13, 20, 23 and 24 from memory without looking at this page.
  2. Build a three-class mini framework: a base test, two page objects and one data-driven test. Run it headless from the command line.
  3. Add a failure screenshot and run one test against a standalone Grid.
  4. Break the tests on purpose: remove a wait, add a sleep, use an absolute XPath. Note the failure message each one gives, because interviewers often ask you to debug a given error.
  5. Explain your code aloud. The round is partly a conversation about why you chose each line.

If you are comparing this page with our other Selenium guides: use the scenario-based Selenium questions for production-style situations, real-time Selenium questions for framework design, advanced Selenium questions for Selenium 4 features and Grid, and most asked Selenium questions for reading exceptions. For the pipeline side, see our guide to continuous testing tools for DevOps.

Training

Test automation sits inside a pipeline, so interviewers for DevOps roles often ask how your Selenium suite runs in Jenkins or another CI server. Our DevOps training and Jenkins training cover that pipeline work. Classes run in Kharadi, Pune, and live online across India.

FAQ

What is asked in a Selenium coding round?

Expect to start a browser, locate elements, wait for a condition, switch windows or frames, fill a form, and structure the code with a page object. Some interviewers add a data-driven test or a Grid run.

Should I write Selenium answers in Java or Python?

Use the language on the job description. Selenium has the same concepts in every binding, so a clear answer in either language scores well. Java is common in enterprise teams and Python in smaller ones.

Do I need to set the chromedriver path in Selenium 4?

Usually not. Selenium Manager ships with the bindings and finds or downloads the right driver automatically. You set a path only when the machine has no internet access.

Should I use implicit or explicit waits?

Use explicit waits and leave the implicit wait at its default of zero. The Selenium documentation warns that mixing the two can cause unpredictable wait times.

Where should assertions go in the Page Object Model?

In the test class. Page objects expose actions and values. The documentation allows one exception, a check in the constructor that the expected page has loaded.

How do I run Selenium tests in parallel?

Give each thread its own driver, usually with a ThreadLocal, and run the tests through your test runner's parallel setting or through Grid. Never share one driver between threads.

Is a certificate enough to pass a Selenium interview?

No. Interviewers test practical skills, which is why this page is built from tasks and not from exam objectives. For how certificates are discussed in interviews, see our Selenium certification interview questions page.

Official references

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.