WebDriver APIs and Commands
WebDriver APIs and Commands Interview with follow-up questions
1. Can you explain the difference between the findElement and findElements commands in WebDriver?
Both findElement and findElements locate web elements on a page using a By locator strategy, but they differ in return type and error behavior.
findElement(By locator)
- Returns the first matching
WebElementon the page. - If no element is found, throws
NoSuchElementExceptionimmediately. - Use when you expect exactly one element and want the test to fail fast if it is missing.
WebElement button = driver.findElement(By.id("submit"));
button.click();
findElements(By locator)
- Returns a
Listcontaining all matching elements. - If no elements are found, returns an empty list — does not throw an exception.
- Use when you need to work with multiple elements (e.g., all rows in a table) or when you want to check if an element exists without risking an exception.
List items = driver.findElements(By.className("menu-item"));
System.out.println("Found: " + items.size());
for (WebElement item : items) {
System.out.println(item.getText());
}
Checking element existence without exception:
// findElements returns empty list (no exception) if not found
boolean isPresent = !driver.findElements(By.id("optional-banner")).isEmpty();
Key differences:
findElement |
findElements |
|
|---|---|---|
| Return type | WebElement |
List |
| No match found | Throws NoSuchElementException |
Returns empty list |
| Multiple matches | Returns first match only | Returns all matches |
| Use case | Single required element | Multiple elements, or optional element check |
> Common interview gotcha: findElement does not guarantee it finds the "right" element when there are multiple matches — it returns whichever the browser encounters first in DOM order. Use more specific locators (ID, unique CSS selector) to be precise.
Follow-up 1
What happens when findElement doesn't find any elements?
When the findElement command doesn't find any elements matching the given locator strategy, it throws a NoSuchElementException. This exception indicates that the element could not be found on the web page.
Follow-up 2
How would you handle such a situation?
To handle the situation when findElement doesn't find any elements, you can use exception handling. You can catch the NoSuchElementException and perform alternative actions or handle the error gracefully. For example, you can log an error message, take a screenshot, or navigate to a different page.
Here's an example in Java:
try {
WebElement element = driver.findElement(By.id("myElement"));
// Perform actions on the element
} catch (NoSuchElementException e) {
// Handle the exception
System.out.println("Element not found");
// Take a screenshot
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Navigate to a different page
driver.get("https://example.com");
}
Follow-up 3
Can you give an example of a situation where you would use findElements instead of findElement?
Yes, one situation where you would use findElements instead of findElement is when you want to verify the presence of multiple elements on a web page. By using findElements, you can check if a list of elements is empty or not, which can be useful for validation purposes.
For example, let's say you have a web page with a list of products and you want to verify if any products are displayed. You can use findElements to find all the product elements and then check if the list is empty or not.
Here's an example in Python:
products = driver.findElements(By.cssSelector(".product"))
if len(products) > 0:
print("Products are displayed")
else:
print("No products found")
2. What is the purpose of the get command in WebDriver?
driver.get(url) is the primary method for navigating to a URL in Selenium WebDriver.
What it does:
- Loads the specified URL in the current browser window.
- Waits for the page load to complete before returning control to the test — specifically, it waits until the browser fires the
document.readyState === "complete"event (equivalent to theonloadevent). - Replaces the current page (does not open a new tab or window).
driver.get("https://www.example.com");
// Control returns here only after the page has fully loaded
WebElement heading = driver.findElement(By.tagName("h1"));
get() vs navigate().to():
Both navigate to a URL, but there is a subtle difference:
| Method | Behavior |
|---|---|
driver.get(url) |
Loads URL; blocks until onload fires |
driver.navigate().to(url) |
Loads URL; also blocks for page load, but is part of the Navigation interface which also provides back(), forward(), refresh() |
In practice, both behave identically for navigation. navigate().to() is preferred when you also need back()/forward() in the same test flow, since they are accessed from the same object.
Common follow-up questions:
- What if the page never fully loads? — The
pageLoadTimeoutsetting determines how long WebDriver waits before throwing aTimeoutException. Default is 300 seconds. Set withdriver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30)). - Does
get()work for file:// URLs? — Yes, local files can be loaded usingfile:///path/to/file.html. - Is
get()sufficient for AJAX-heavy SPAs? — Not always. Theonloadevent fires when the initial HTML loads, but dynamic content loaded via AJAX may not be ready. Use explicit waits afterget()for SPA content.
Follow-up 1
Can you give an example of how to use the get command?
Sure! Here's an example of how to use the get command in WebDriver using Python:
from selenium import webdriver
# Create a new instance of the Firefox driver
driver = webdriver.Firefox()
# Navigate to a specific URL
driver.get('https://www.example.com')
Follow-up 2
What happens if the URL provided to the get command is invalid?
If the URL provided to the get command is invalid or cannot be reached, WebDriver will throw an exception. The specific exception may vary depending on the programming language and WebDriver implementation being used. It is important to handle such exceptions properly in order to handle any errors that may occur during navigation.
Follow-up 3
Is there a way to verify that the get command has successfully navigated to the desired webpage?
Yes, there are several ways to verify that the get command has successfully navigated to the desired webpage. One common approach is to check the current URL of the WebDriver after the get command has been executed. If the current URL matches the expected URL, it can be assumed that the navigation was successful. Additionally, you can also check for specific elements or content on the webpage to confirm that it has loaded correctly.
3. Can you explain the difference between the close and quit commands in WebDriver?
close() and quit() both end browser interactions, but they behave differently and are used in different scenarios.
driver.close()
- Closes the currently focused browser window or tab.
- If there are multiple windows or tabs open in the session, only the current one is closed. The WebDriver session remains active.
- Does not end the WebDriver session — the driver object is still valid and can be used to switch to and interact with remaining windows.
// Example: close a popup window and switch back to the main window
String mainHandle = driver.getWindowHandle();
// ... open popup ...
driver.close(); // closes popup
driver.switchTo().window(mainHandle); // back to main window
driver.quit()
- Closes all browser windows and tabs opened by the WebDriver session.
- Ends the WebDriver session and releases all associated resources (driver process, browser process).
- Should always be called in teardown to prevent browser/driver processes from leaking.
@AfterMethod // TestNG teardown
public void tearDown() {
if (driver != null) {
driver.quit();
}
}
Key differences:
close() |
quit() |
|
|---|---|---|
| Windows closed | Current window/tab only | All windows/tabs |
| Session ended | No | Yes |
| Driver usable after | Yes (if other windows remain) | No |
| Use case | Closing specific windows during a test | Final teardown |
Common interview gotcha:
If you call close() when only one window is open, it closes the browser but the WebDriver session may not be fully cleaned up on some browsers. Always use quit() in @After / tearDown methods. Failing to call quit() causes browser and driver processes to accumulate, consuming memory and potentially causing port conflicts.
Follow-up 1
What happens if you use the quit command while multiple windows are open?
If the quit command is used while multiple windows are open, WebDriver will close all the windows and terminate the session. It is important to note that any subsequent commands or operations on the WebDriver instance after using the quit command will result in an error.
Follow-up 2
In what situations would you use close instead of quit?
The close command is typically used when you want to close a specific window or tab in the browser, without terminating the entire WebDriver session. This can be useful when working with multiple windows or tabs and you only want to close a specific one while keeping the others open.
Follow-up 3
Can you give an example of how to use the quit command?
Sure! Here's an example of how to use the quit command in Python with Selenium WebDriver:
from selenium import webdriver
# Create a new instance of the WebDriver
driver = webdriver.Firefox()
# Perform some actions with the WebDriver
# ...
# Close all windows and terminate the session
driver.quit()
4. What is the navigate command in WebDriver and how is it used?
The navigate() method returns a WebDriver.Navigation object that provides browser history and URL navigation methods. It is the preferred approach when you need to navigate back, forward, or refresh within a test.
Available methods:
driver.navigate().to("https://example.com"); // Navigate to URL
driver.navigate().back(); // Go back in history
driver.navigate().forward(); // Go forward in history
driver.navigate().refresh(); // Refresh current page
navigate().to() vs driver.get():
Both load a URL. The practical difference:
driver.get(url)is a shorthand for simple page loads.driver.navigate().to(url)is part of the Navigation API, so you can chain with.back()/.forward()without breaking context.- Both wait for the page load event (
document.readyState === "complete") before returning.
navigate().back() and navigate().forward():
These simulate clicking the browser's Back and Forward buttons. They work with the browser's session history:
driver.get("https://page1.com");
driver.get("https://page2.com");
driver.navigate().back(); // returns to page1.com
driver.navigate().forward(); // returns to page2.com
navigate().refresh():
Reloads the current page. Equivalent to pressing F5 in the browser. Useful for testing page state after an action or verifying that data persists after reload.
driver.navigate().refresh();
Practical use in tests:
// Test that a form submission is not re-submitted on refresh (PRG pattern)
driver.findElement(By.id("submit")).click();
String urlAfterSubmit = driver.getCurrentUrl();
driver.navigate().refresh();
// Verify no duplicate submission warning
Common follow-up: After navigate().back() or .refresh(), previously found WebElement references become stale. Re-locate elements after navigation to avoid StaleElementReferenceException.
Follow-up 1
Can you give an example of how to use the navigate command to go back to a previous page?
To use the navigate command to go back to a previous page, you can use the back() method of the navigate command. Here's an example:
from selenium import webdriver
# Create a new instance of the Firefox driver
driver = webdriver.Firefox()
# Navigate back to the previous page
driver.navigate().back()
Follow-up 2
What other actions can you perform with the navigate command?
Apart from navigating to a specific URL and going back to a previous page, the navigate command in WebDriver also allows you to perform the following actions:
- Forward: Use the
forward()method to navigate forward in the browser history. - Refresh: Use the
refresh()method to refresh the current page.
Example:
from selenium import webdriver
# Create a new instance of the Firefox driver
driver = webdriver.Firefox()
# Navigate forward in the browser history
driver.navigate().forward()
# Refresh the current page
driver.navigate().refresh()
Follow-up 3
How does the navigate command differ from the get command?
The navigate command and the get command in WebDriver are used to open a specific URL, but they have some differences:
The
navigate().to(url)method of the navigate command is used to open a new URL in the current browser window. It allows you to navigate to a different domain or a different page within the same domain.The
get(url)method of the WebDriver instance is also used to open a URL, but it creates a new browser window or tab. It does not allow you to navigate to a different domain or a different page within the same domain.
Example:
from selenium import webdriver
# Create a new instance of the Firefox driver
driver = webdriver.Firefox()
# Open a URL in the current browser window
driver.navigate().to('https://www.example.com')
# Open a URL in a new browser window
driver.get('https://www.example.com')
5. Can you explain how to use the WebDriver APIs to interact with web elements?
Selenium WebDriver provides a rich set of APIs for locating and interacting with web elements. The general pattern is: locate → interact → verify.
Locating elements:
WebElement el = driver.findElement(By.id("username"));
WebElement el = driver.findElement(By.name("email"));
WebElement el = driver.findElement(By.cssSelector(".btn-primary"));
WebElement el = driver.findElement(By.xpath("//button[@type='submit']"));
WebElement el = driver.findElement(By.linkText("Sign In"));
Basic interactions on a WebElement:
el.click(); // Click the element
el.sendKeys("[email protected]"); // Type text (clears nothing — appends)
el.clear(); // Clear text field content
el.submit(); // Submit a form (on form elements)
String text = el.getText(); // Visible text content
String value = el.getAttribute("value"); // HTML attribute value
String cls = el.getAttribute("class");
boolean shown = el.isDisplayed(); // Visible on page
boolean enabled = el.isEnabled(); // Not disabled
boolean checked = el.isSelected(); // Checked (checkbox/radio)
Dropdown (select elements):
Select dropdown = new Select(driver.findElement(By.id("country")));
dropdown.selectByVisibleText("United States");
dropdown.selectByValue("us");
dropdown.selectByIndex(2);
List options = dropdown.getOptions();
Complex interactions with Actions class:
Actions actions = new Actions(driver);
// Hover over an element
actions.moveToElement(menuItem).perform();
// Drag and drop
actions.dragAndDrop(source, target).perform();
// Right-click (context menu)
actions.contextClick(element).perform();
// Double-click
actions.doubleClick(element).perform();
// Key chord (e.g., Ctrl+A)
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
Selenium 4 relative locators:
WebElement emailField = driver.findElement(By.id("email"));
WebElement passwordField = driver.findElement(
RelativeLocator.with(By.tagName("input")).below(emailField)
);
For elements that don't respond to standard Selenium interactions (e.g., hidden elements, canvas), use JavascriptExecutor as a fallback:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
Follow-up 1
How would you use WebDriver to interact with a dropdown menu?
To interact with a dropdown menu using WebDriver, you can first locate the dropdown element using one of the locator strategies provided by the By class. Once you have located the dropdown element, you can create an instance of the Select class and use its methods to select an option from the dropdown.
Here's an example of how to select an option by visible text:
WebElement dropdown = driver.findElement(By.id("myDropdown"));
Select select = new Select(dropdown);
select.selectByVisibleText("Option 1");
Follow-up 2
How would you use WebDriver to submit a form?
To submit a form using WebDriver, you can locate the form element using one of the locator strategies provided by the By class. Once you have located the form element, you can use the submit() method to submit the form.
Here's an example:
WebElement form = driver.findElement(By.id("myForm"));
form.submit();
Follow-up 3
Can you give an example of how to use WebDriver to handle a checkbox?
To handle a checkbox using WebDriver, you can locate the checkbox element using one of the locator strategies provided by the By class. Once you have located the checkbox element, you can use the click() method to toggle its state.
Here's an example:
WebElement checkbox = driver.findElement(By.id("myCheckbox"));
checkbox.click();
Live mock interview
Mock interview: WebDriver APIs and Commands
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.