These Selenium interview questions for 1 year of experience target testers who have automated real flows for a few months up to a year. Expect questions on synchronisation and waits, dropdowns, alerts and file uploads, windows and frames, the Actions class, JavaScriptExecutor and screenshots, and interviewers will ask what you did when something didn't work.

Selenium interview questions by experience: Freshers · 1 year · 3 years · 5 years
Planning your learning? Follow the Selenium automation testing roadmap.

Synchronization & Waits

1. Why are waits necessary in Selenium automation?

Waits handle the timing gap between test script actions and browser/application response.

  • Web pages are dynamic — elements load asynchronously via AJAX, JavaScript, API calls
  • Without waits: ElementNotVisibleException, NoSuchElementException when script runs faster than page renders
  • Network latency: Elements may load at different speeds in different environments (local vs CI vs staging)
  • Single-page applications (SPAs like React/Angular): Elements appear/disappear dynamically without full page reload
  • Animation delays: Elements may be in the DOM but not yet visible/clickable due to CSS transitions

2. Explain Implicit Wait, Explicit Wait, and Fluent Wait in detail.

Three types of waits, each with different use cases:

IMPLICIT WAIT

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Applied globally to ALL findElement calls in the driver session
WebDriver polls DOM repeatedly until element found or timeout reached
Set once — applies for entire test session

Limitation: Cannot wait for specific conditions (visibility, clickability)

EXPLICIT WAIT

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
WebElement el = wait.until(ExpectedConditions.elementToBeClickable(By.id("btn")));
Applied to specific elements with specific conditions
More precise and reliable than implicit wait

ExpectedConditions available: visibilityOf, elementToBeClickable, presenceOfElement, textToBe, alertIsPresent, etc.

FLUENT WAIT

Wait<WebDriver> wait = new FluentWait<>(driver)
  .withTimeout(Duration.ofSeconds(30))
  .pollingEvery(Duration.ofSeconds(2))
  .ignoring(NoSuchElementException.class);
Custom polling interval (check every 2 seconds)
Can ignore specific exceptions during wait period
Most flexible — use for complex, irregular loading scenarios

3. What are all the ExpectedConditions available in Selenium?

ExpectedConditions provides pre-built conditions for WebDriverWait:

  • Visibility: visibilityOf(element), visibilityOfElementLocated(locator), visibilityOfAllElements(list)
  • Presence (in DOM, may not be visible): presenceOfElementLocated(locator), presenceOfAllElementsLocatedBy(locator)
  • Clickability: elementToBeClickable(element or locator)
  • Invisibility: invisibilityOf(element), invisibilityOfElementLocated(locator)
  • Text: textToBe(locator, text), textToBePresentInElement(element, text), textToBePresentInElementValue(locator, text)
  • Alerts: alertIsPresent()
  • Frame: frameToBeAvailableAndSwitchToIt(locator or index or name)
  • Selection: elementToBeSelected(element), elementSelectionStateToBe(element, true/false)
  • Attribute: attributeContains(locator, attr, value), attributeToBe(locator, attr, value)
  • URL: urlContains(fragment), urlToBe(url), urlMatches(regex)
  • Title: titleContains(text), titleIs(text)
  • Staleness: stalenessOf(element) — wait until element is no longer attached to DOM
  • Number of windows: numberOfWindowsToBe(int)

4. Why should you NEVER mix Implicit Wait and Explicit Wait?

Mixing implicit and explicit waits causes unpredictable, counterproductive behavior.

  • Problem: When both are set, WebDriver uses the LONGER of the two timeouts — not the explicit wait you specified
  • Example: implicitlyWait(10s) + explicit wait(5s) — element not found scenario waits 10 seconds, not 5
  • This leads to tests taking much longer than expected and confusion in debugging
  • Rule: Use ONLY explicit waits for all element interactions. Never set implicit wait if you use explicit.
  • Alternative: If you need a global default, set implicit wait to 0 and use explicit waits consistently
  • Fluent Wait with polling is the most reliable solution for dynamic SPAs
Advertisement

Handling Web Elements — Dropdowns, Alerts, Files

5. How do you handle HTML select dropdowns in Selenium?

Use the Select class from org.openqa.selenium.support.ui.Select for HTML <select> elements.

Select select = new Select(driver.findElement(By.id("country")));
  • selectByVisibleText("India"): Selects option by its displayed text
  • selectByValue("IN"): Selects option by its value attribute
  • selectByIndex(2): Selects option by its 0-based index
  • getOptions(): Returns List<WebElement> of all options
  • getAllSelectedOptions(): Returns List of all selected options (for multi-select)
  • getFirstSelectedOption(): Returns the currently selected option
  • isMultiple(): Returns true if <select multiple> — allows multiple selections
  • deselectAll(): Deselects all selected options (multi-select only)
  • deselectByVisibleText(), deselectByValue(), deselectByIndex(): Deselect specific options
  • For custom dropdowns (not <select>): Click to open dropdown div, then click the desired option

6. How do you handle JavaScript alerts, confirms, and prompts?

Selenium handles browser-native JS alerts using the Alert interface.

Simple Alert (OK only): Alert alert = driver.switchTo().alert(); alert.accept();

  • Confirm Dialog (OK + Cancel): alert.accept() for OK, alert.dismiss() for Cancel
  • Prompt Dialog (text input): alert.sendKeys("My Input"); alert.accept();
  • Get alert text: String message = alert.getText();
  • Always switch to alert BEFORE interacting with page elements when alert is present
  • UnhandledAlertException: Thrown if you try to interact with page while alert is open
  • Wait for alert: wait.until(ExpectedConditions.alertIsPresent()); then switchTo().alert()
  • Authentication popups: Use URL format https://username:password@site.com for basic auth

7. How do you handle file upload in Selenium?

File upload depends on whether it uses a standard HTML input or a custom dialog.

  • Standard HTML input type=file: element.sendKeys("/absolute/path/to/file.txt"); — No dialog opens
  • This works because sendKeys() on file input sets the file path directly
  • Make sure the file input is visible (not hidden) or use JS to make it visible first
  • Multiple files: element.sendKeys("/path/file1.txt\n/path/file2.txt");
  • Robot class: For OS-level file dialogs — type path using Robot.keyPress() and StringSelection
  • AutoIt: Windows-only tool for handling Windows file dialogs that can't be controlled by Selenium
  • Sikuli: Image-based automation for GUI file dialogs
  • Verify upload: Check success message, or verify file appears in list after upload

8. How do you handle checkboxes and radio buttons in Selenium?

Checkboxes and radio buttons are simple to interact with but have specific patterns:

  • Check/select: element.click() — if not already checked

Always check current state first: if (!element.isSelected()) { element.click(); }

Uncheck: if (element.isSelected()) { element.click(); }

  • Verify state: boolean isChecked = element.isSelected();
  • For radio buttons: radio.click() — selecting one auto-deselects others in same group

Get all radio buttons: List<WebElement> radios = driver.findElements(By.name("gender"));

Select by value: for(WebElement r : radios){ if(r.getAttribute("value").equals("male")) r.click(); }

  • Custom checkboxes (span/div styled): Click the visible element, not the hidden input — use parent element

Browser Windows, Tabs & Frames

9. How do you handle multiple browser windows and tabs in Selenium?

Each window/tab has a unique handle (String ID). Use getWindowHandles() to manage them.

Get current window: String mainWindow = driver.getWindowHandle();

Get all windows: Set<String> allWindows = driver.getWindowHandles();

Switch to new window

for(String handle : allWindows) {
  if(!handle.equals(mainWindow)) { driver.switchTo().window(handle); break; }
}

Switch back: driver.switchTo().window(mainWindow);

Open new tab (Selenium 4): driver.switchTo().newWindow(WindowType.TAB);

Open new window (Selenium 4): driver.switchTo().newWindow(WindowType.WINDOW);

Close current tab and switch back: driver.close(); driver.switchTo().window(mainWindow);

  • Best Practice: Always switch back to main window after finishing work in popup window

10. How do you handle iFrames in Selenium? What are nested iFrames?

iFrames are HTML documents embedded within another HTML page. Selenium cannot interact with iFrame elements without first switching to the iFrame context.

Switch by index: driver.switchTo().frame(0); — first iFrame on page (0-indexed)

Switch by name/id: driver.switchTo().frame("iframeName");

Switch by WebElement: WebElement fr = driver.findElement(By.id("myFrame")); driver.switchTo().frame(fr);

Switch back to main page: driver.switchTo().defaultContent();

Switch to parent frame (one level up): driver.switchTo().parentFrame();

  • Nested iFrames: Switch to outer frame first, then switch to inner frame. To go back, call defaultContent().
  • Common error: NoSuchFrameException — check frame ID/name using browser DevTools

How to detect iFrames: driver.findElements(By.tagName("iframe")) — check if list is not empty

Actions Class — Mouse & Keyboard

11. What is the Actions class? Explain all its methods with examples.

Actions class (org.openqa.selenium.interactions.Actions) handles complex user gestures that simple click/sendKeys cannot.

  • Actions actions = new Actions(driver);

MOUSE ACTIONS

  • moveToElement(element): Hover over element (triggers mouseover/mouseenter events)
  • click(element): Click element (equivalent to WebElement.click() but chainable)
  • doubleClick(element): Double-click an element
  • contextClick(element): Right-click to open context menu
  • clickAndHold(element): Press and hold mouse button
  • release(): Release held mouse button
  • dragAndDrop(source, target): Click-hold source, move to target, release
  • dragAndDropBy(source, xOffset, yOffset): Drag by pixel offset
  • moveByOffset(x, y): Move mouse relative to current position

KEYBOARD ACTIONS

  • sendKeys(element, "text"): Type into element
  • keyDown(Keys.CONTROL): Hold down a modifier key
  • keyUp(Keys.CONTROL): Release a modifier key
  • Key combo: actions.keyDown(Keys.CONTROL).sendKeys('a').keyUp(Keys.CONTROL).perform(); // Select all

ALWAYS call .perform() at the end to execute the action chain!

12. How do you perform drag and drop in Selenium? What if dragAndDrop() doesn't work?

Drag and drop can be tricky — the standard API often fails on modern web frameworks.

  • Standard approach: new Actions(driver).dragAndDrop(sourceEl, targetEl).perform();
  • By offset: new Actions(driver).dragAndDropBy(sourceEl, 300, 0).perform();
  • If standard fails (common with HTML5 drag-drop): Use JavaScript simulation
  • JS approach: Dispatch dragstart, dragover, drop events manually using executeScript()
  • Alternative: clickAndHold → pause → moveToElement → release pattern
actions.clickAndHold(source).pause(Duration.ofMillis(500)).moveToElement(target).pause(Duration.ofMillis(500)).release().perform();
  • Robot class: Use java.awt.Robot for OS-level mouse events as last resort
  • Root cause: HTML5 drag-and-drop uses DataTransfer API which standard Actions doesn't support

13. How do you scroll a web page using Selenium?

Selenium 4 has native scroll support. For Selenium 3, use JavaScript.

  • Scroll using JavaScript (Selenium 3 & 4):
js.executeScript("window.scrollTo(0, document.body.scrollHeight)"); // Scroll to bottom
js.executeScript("window.scrollBy(0, 500)"); // Scroll down 500px
js.executeScript("arguments[0].scrollIntoView(true);", element); // Scroll to element

Scroll using Actions (Selenium 4)

new Actions(driver).scrollToElement(element).perform();
new Actions(driver).scrollByAmount(0, 500).perform(); // Scroll down 500px
  • Scroll within a scrollable div (not window):
js.executeScript("arguments[0].scrollTop = arguments[0].scrollHeight", scrollableDiv);
  • Best practice: Use scrollIntoView before clicking elements that might be below viewport

JavaScript Executor

14. What is JavaScriptExecutor? When should you use it and when avoid it?

JavaScriptExecutor interface executes JavaScript code directly in the browser context.

  • Cast driver: JavascriptExecutor js = (JavascriptExecutor) driver;
  • Execute script: js.executeScript("return document.title;");
  • Pass arguments: js.executeScript("arguments[0].click();", element);

WHEN TO USE

  • Clicking elements that are not clickable via WebDriver (hidden, overlapping, etc.)
  • Scrolling page or specific container
  • Setting/getting element values that CSS/HTML attributes don't expose
  • Getting computed styles: js.executeScript("return window.getComputedStyle(arguments[0]).color", el)
  • Triggering events manually: js.executeScript("arguments[0].dispatchEvent(new Event(\"change\"))", el)
  • Bypassing overlays or popups that block element interaction

WHEN TO AVOID

  • Clicking normal visible buttons — WebElement.click() is more reliable and realistic
  • Over-using JS bypasses validation that real users would encounter
  • JS clicks don't trigger some browser events that WebDriver clicks do

15. How do you use executeAsyncScript() and when is it needed?

executeAsyncScript() is used when JavaScript code involves callbacks or async operations.

  • executeScript() is synchronous — script must complete and return immediately
  • executeAsyncScript() waits for a callback — used for AJAX responses, timeouts, Promises
  • Must call arguments[arguments.length-1]() to signal completion
  • Example: Wait for Angular to finish: js.executeAsyncScript("var cb=arguments[arguments.length-1]; angular.getTestability(document.body).whenStable(cb);")

Set script timeout first: driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(10));

  • Use case: Waiting for custom JavaScript operations to complete before continuing test
  • Alternative: Most modern frameworks — Explicit Wait handles async element loading better

Screenshots

16. How do you capture screenshots in Selenium? Explain all approaches.

Screenshots are essential for test failure diagnosis and reporting.

FULL VIEWPORT SCREENSHOT

  • TakesScreenshot ts = (TakesScreenshot) driver;
  • File srcFile = ts.getScreenshotAs(OutputType.FILE);
  • FileUtils.copyFile(srcFile, new File("screenshots/test_" + timestamp + ".png"));
  • SCREENSHOT TO BASE64 (for HTML reports):
  • String base64 = ts.getScreenshotAs(OutputType.BASE64);

// Embed in report: 'data:image/png;base64,' + base64

ELEMENT-LEVEL SCREENSHOT (Selenium 4)

  • File elementFile = element.getScreenshotAs(OutputType.FILE);

FULL PAGE SCREENSHOT (AShot library)

  • Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
  • ImageIO.write(screenshot.getImage(), "PNG", new File("fullpage.png"));

BEST PRACTICE: Capture in TestNG Listener's onTestFailure() method with timestamp in filename

Quick-Fire Questions

Short answers to revise the night before.

17. What are locators in Selenium?

Mechanisms to find web elements. Types: ID, Name, CSS Selector, XPath, LinkText, PartialLinkText, TagName.

18. What is the difference between findElement and findElements?

findElement returns a single WebElement (throws exception if not found). findElements returns a List — empty list if nothing found.

19. What is XPath and what are its types?

XPath locates elements in an XML/HTML tree. Types: Absolute XPath (starts with /) and Relative XPath (starts with //) — always prefer relative.

20. What is implicit wait?

A global wait setting that tells Selenium to wait up to N seconds for any element before throwing NoSuchElementException.

21. What is explicit wait?

Wait applied to a specific element with a specific condition (e.g., elementToBeClickable). Uses WebDriverWait + ExpectedConditions.

22. What is Fluent Wait?

Advanced explicit wait that polls at regular intervals and can ignore specific exceptions. Best for dynamic elements.

23. What happens if you use Thread.sleep()?

Hard pause that freezes test execution regardless of element state. Slows tests and is unreliable. Avoid in production code.

24. What is the difference between click() and submit()?

click() works on any element. submit() is for form elements — submits the entire form.

25. How do you handle alerts?

driver.switchTo().alert() — then use accept(), dismiss(), getText(), or sendKeys().

26. What is JavascriptExecutor?

An interface that runs JavaScript in the browser. Used for scrolling, clicking hidden elements, or getting browser properties.

27. What is the Actions class used for?

For advanced mouse/keyboard actions: hover, double-click, right-click, drag-and-drop, key combinations.

28. What is TestNG?

A testing framework for Java. Provides annotations like @Test, @BeforeMethod, @AfterMethod to organize and run tests.

29. What is the difference between @BeforeMethod and @BeforeClass?

@BeforeMethod runs before EACH test. @BeforeClass runs once before all tests in the class.

30. What is the difference between hard assertion and soft assertion?

Hard assertion (Assert) stops test immediately on failure. Soft assertion (SoftAssert) continues and reports all failures at the end.

31. How do you take a screenshot in Selenium?

Cast driver to TakesScreenshot, call getScreenshotAs(OutputType.FILE), then copy to a file path.

32. What is sendKeys() used for?

To type text into input fields, text areas, or to send keyboard keys like ENTER, TAB, etc.

33. What does getText() return?

Returns the visible inner text of a web element.

34. What is getAttribute() used for?

Gets the value of an HTML attribute of an element. E.g., getAttribute("href") on a link.

35. How do you verify if an element is displayed?

Use isDisplayed() which returns true if the element is visible on the page.

How to Prepare with 1 Year of Experience

  • Be able to explain one flaky test you fixed and what caused it (usually a wait or a locator).
  • Know when you'd use JavaScriptExecutor and why it's a last resort.
  • Revise the fresher questions too, and look ahead to the questions for 3 years of experience: framework design comes next.