Selenium Interview Questions for Freshers
1. What is Selenium, and why is it used?
Its key advantage is that it enables testing of modern web applications without the need for manual interaction.
// Example in Java
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
2. What are the components of Selenium?
Selenium has four major components:
- Selenium IDE: A browser plugin used for record-and-playback testing.
- Selenium WebDriver: The core API that allows you to write test scripts.
- Selenium Grid: Supports distributed test execution across multiple machines and browsers.
- Selenium RC (Deprecated): An older tool that has now been replaced by WebDriver.
3. What are the limitations of Selenium?
- It only supports web-based applications, not desktop or mobile apps (unless used with Appium).
- No built-in reporting mechanism — external tools are needed.
- Handling CAPTCHAs or barcode scanners requires workarounds.
- Steep learning curve for advanced automation.
4. What is the difference between Selenium 2.0 and 3.0?
Think of Selenium 3.0 as a cleaner, more modern WebDriver-centric framework.
5. What are locators in Selenium?
- ID
- Name
- Class Name
- Tag Name
- Link Text & Partial Link Text
- XPath
- CSS Selector
Choosing the right locator improves script stability and execution speed.
6. What is the difference between findElement and findElements?
findElement
returns the first matching element and throws an exception if not found, while findElements
returns a list of all matching elements and an empty list if none are found.
// Returns one WebElement
WebElement button = driver.findElement(By.id("submit"));
// Returns a list
List links = driver.findElements(By.tagName("a"));
7. How do you launch a browser using Selenium WebDriver?
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
You can similarly use FirefoxDriver
, EdgeDriver
, etc.
8. How do you handle browser navigation in Selenium?
driver.navigate().to("https://example.com");
driver.navigate().back();
driver.navigate().forward();
driver.navigate().refresh();
These mimic how users interact with a browser.
9. What is an XPath, and how is it used in Selenium?
// Absolute XPath
/html/body/div[2]/input
// Relative XPath
//input[@id='username']
10. How do you handle dynamic elements in Selenium?
contains()
, starts-with()
, or combine attributes that remain constant.
// Using contains
//input[contains(@id, 'user')]
// Using starts-with
//button[starts-with(@class, 'submit')]
This ensures selectors remain stable even if parts of the attribute values change.
Related: Python Selenium Interview Questions with Answers
Selenium Interview Questions for Experienced
11. How do you manage waits in Selenium WebDriver?
- Implicit Wait: Waits for a defined time before throwing NoSuchElementException.
- Explicit Wait: Waits for a specific condition to occur.
- Fluent Wait: Offers more control over polling intervals and exception handling.
// Example of Explicit Wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("login")));
12. What is the difference between driver.close() and driver.quit()?
driver.close()
– Closes the current browser window.driver.quit()
– Quits the entire browser session, closing all associated windows and ending the WebDriver process.
Use quit()
to ensure complete cleanup, especially after test suite execution.
13. How do you capture screenshots in Selenium?
TakesScreenshot
interface:
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("screenshot.png"));
You can automate this on test failures using listeners or try-catch blocks.
14. What are DesiredCapabilities in Selenium?
Options
classes like ChromeOptions
, FirefoxOptions
.
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
15. How do you handle dropdowns in Selenium?
Select
class for handling dropdowns:
Select select = new Select(driver.findElement(By.id("dropdownId")));
select.selectByVisibleText("Option 1");
select.selectByIndex(2);
select.selectByValue("opt2");
16. How do you handle multiple browser windows?
String parent = driver.getWindowHandle();
for (String handle : driver.getWindowHandles())
// After actions, return to parent
driver.switchTo().window(parent);
17. How do you switch between frames?
driver.switchTo().frame("frameName");
// or
WebElement frame = driver.findElement(By.tagName("iframe"));
driver.switchTo().frame(frame);
// To return
driver.switchTo().defaultContent();
18. How do you handle alerts in Selenium?
Alert
interface to interact with pop-ups:
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept(); // or alert.dismiss();
You can also send text in prompt alerts using alert.sendKeys("text")
.
19. How can you perform mouse hover actions?
Actions
class to simulate mouse interactions:
Actions actions = new Actions(driver);
WebElement element = driver.findElement(By.id("menu"));
actions.moveToElement(element).perform();
This is useful for revealing hidden dropdowns or tooltips.
20. How do you validate broken links using Selenium?
<a>
tags and check HTTP status codes using Java’s HttpURLConnection
:
List links = driver.findElements(By.tagName("a"));
for (WebElement link : links)
}
21. How do you manage test data in Selenium automation?
- Hardcoded: Directly within test scripts (not scalable).
- External files: Excel, CSV, JSON, or XML using libraries like Apache POI or Jackson.
- DataProvider: In TestNG for parameterisation.
22. What is Page Object Model (POM)?
public class LoginPage
}
It improves maintainability and readability.
23. How do you handle exceptions in Selenium scripts?
try catch (NoSuchElementException e)
It’s a good practice to capture screenshots and continue test flow.
24. What is the role of listeners in Selenium?
IAnnotationTransformer
, ITestListener
, and ISuiteListener
can log, capture screenshots, or rerun failed tests.
They help in better debugging and reporting mechanisms.
25. How do you integrate Selenium with Jenkins?
- Push Selenium scripts to a Git repository.
- Create a Jenkins job, link Git repo, and trigger builds.
- Use Maven/TestNG plugins for execution and reports.
This enables continuous testing and automated feedback loops.
Selenium Automation Framework Questions
26. What is a Selenium Framework and why do we use it?
It allows test engineers to develop scalable, maintainable, and reusable automation test scripts by enforcing uniformity in coding standards and providing a systematic way to handle test data, test execution, and reporting.
There are several types of Selenium frameworks used in the industry:
- Data-Driven Framework: Focuses on externalising test data using Excel, CSV, or databases. Tests are driven by data rather than hard-coded inputs, increasing flexibility and reducing duplication.
- Keyword-Driven Framework: Uses predefined keywords (like click, input, verify) that are mapped to actions. Testers, even with limited coding skills, can write tests using these keywords in spreadsheets.
- Hybrid Framework: Combines the advantages of both Data-Driven and Keyword-Driven frameworks, allowing for greater flexibility and broader use-case coverage.
// Pseudocode for data-driven test
String username = excelReader.getCellValue("Sheet1", 1, 0);
driver.findElement(By.id("user")).sendKeys(username);
27. What is TestNG and how is it used in Selenium?
In the context of Selenium, TestNG plays a crucial role by organising test cases, supporting parallel execution, managing test dependencies, and generating detailed HTML reports. Its annotation-based structure allows developers to control the test lifecycle precisely.
Using TestNG with Selenium also provides seamless integration with tools like Maven, Jenkins, and Allure for CI/CD workflows.
@Test
public void testLogin()
28. What is the use of annotations in TestNG?
@BeforeSuite
and@AfterSuite
: Run once before and after all tests in the suite.@BeforeClass
and@AfterClass
: Run once before and after each test class.@BeforeMethod
and@AfterMethod
: Run before and after each test method.@Test
: Marks the actual test method.
This provides fine-grained control over how and when each piece of code is executed in relation to others.
@BeforeMethod
public void setup()
29. How do you implement a Data-Driven Framework using TestNG?
@DataProvider
annotation which allows feeding multiple sets of data to a single test method. This decouples test logic from the input data and supports executing tests repeatedly for different inputs.
@DataProvider(name="loginData")
public Object[][] getData() ,
};
}
@Test(dataProvider="loginData")
public void testLogin(String user, String pass)
30. What is the difference between TestNG and JUnit in Selenium?
- TestNG provides built-in support for parallel test execution and dependency management, while JUnit requires external workarounds.
- Data-driven testing is more straightforward in TestNG using
@DataProvider
, whereas JUnit relies on parameterised test classes. - TestNG’s reporting capabilities and annotations are more advanced and flexible compared to JUnit.
31. What is a Hybrid Framework in Selenium?
It enables separation of test logic, test data, and test keywords, resulting in reusable components and better collaboration between technical and non-technical team members.
The framework is ideal for large-scale applications where high flexibility and modularity are essential.
32. How do you maintain modularity in Selenium framework?
This can be achieved by using utility classes for common actions, following the Page Object Model to encapsulate page-specific behaviour, and ensuring that the test logic is kept separate from business logic.
Modularity allows teams to scale easily and maintain code with minimal effort.
33. What are the reporting tools used with Selenium?
- TestNG Reports: Provides HTML and XML reports by default.
- Extent Reports: Offers a rich UI with screenshots, logs, and status-based visuals for passed/failed/skipped tests.
- Allure Reports: Known for its modern interface, support for behavior-driven development (BDD), and CI integration.
34. How do you run Selenium scripts in parallel?
parallel
attribute in the testng.xml
configuration file. You can run tests across multiple classes, methods, or test tags simultaneously by setting a thread-count
.
<suite name="ParallelSuite" parallel="tests" thread-count="2">
<test name="ChromeTests"> ... </test>
<test name="FirefoxTests"> ... </test>
</suite>
35. How do you manage browser compatibility in Selenium tests?
By using tools like WebDriverManager, developers can automatically manage driver binaries. Parameterising the test suite using TestNG or configuration files allows you to run the same test across browsers.
if(browser.equals("chrome")) else if(browser.equals("firefox"))
36. What is the Page Object Model (POM) in Selenium?
By separating test logic from UI locators, it becomes easier to maintain the framework, especially when the UI changes frequently.
public class LoginPage
public void login(String user, String pass)
}
37. How does Maven help in Selenium test automation?
pom.xml
file.
Maven fetches them automatically, ensuring all team members use the same versions. Additionally, Maven helps in organising the project structure, running test suites via command line, and integrating with CI/CD pipelines like Jenkins.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.8.0</version>
</dependency>
38. What is the role of Jenkins in Selenium automation?
By configuring Selenium projects as Jenkins jobs, testers can run their test suites automatically after every code check-in or at scheduled times.
It provides a dashboard to track pass/fail trends and supports plugin integration for reporting tools like Allure and Extent.
# Typical Jenkins setup:
- Pull latest code from GitHub
- Build project using Maven
- Run Selenium tests with TestNG
- Generate reports and email results
39. What are some best practices for designing a Selenium framework?
- Use Page Object Model to separate test logic from UI locators.
- Incorporate reusable utility methods for waits, logging, and assertions.
- Manage test data externally (Excel, JSON, or DB) using DataProviders.
- Use Maven or Gradle for build management.
- Integrate reporting tools like Extent or Allure for better visibility.
- Run tests in parallel to save time using TestNG or Selenium Grid.
- Handle exceptions gracefully and use proper logging mechanisms.
Related Read: JavaScript ES6+ Features You Must Know for Interviews in [ 2025 ]
40. What is Selenium Grid and how does it help in framework execution?
A Grid setup consists of a Hub (which controls execution) and multiple Nodes (which execute tests). Selenium Grid fits well in frameworks that need to validate UI behaviour across different environments simultaneously.
// Set desired capabilities for Firefox on Grid
DesiredCapabilities cap = DesiredCapabilities.firefox();
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), cap);
41. How do you implement logging in a Selenium framework?
Logger log = Logger.getLogger("MyLogger");
log.info("Login page opened successfully");
42. What is SoftAssert in TestNG and why is it useful?
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(title, "Dashboard");
softAssert.assertTrue(userIcon.isDisplayed());
softAssert.assertAll();
43. What is the role of listeners in Selenium TestNG?
public class CustomListener extends TestListenerAdapter
}
44. How do you parameterise Selenium tests using TestNG XML?
testng.xml
and accessed using the @Parameters
annotation. This is particularly useful for data-driven and environment-based testing.
// testng.xml
<parameter name=\"browser\" value=\"chrome\"/>
// Test file
@Parameters(\"browser\")
public void setup(String browserName)
}
45. How do you handle configuration management in Selenium projects?
// config.properties
browser=chrome
url=https://example.com
// Java code
Properties prop = new Properties();
prop.load(new FileInputStream(\"config.properties\"));
String baseUrl = prop.getProperty(\"url\");
Related Read: HTML and CSS Interview Questions & Answers [ 2025 ]
Selenium Coding and Scenario-Based Questions
46. How do you handle multiple browser windows in Selenium?
getWindowHandles()
to retrieve all handles and switch context using switchTo().window()
. This is crucial in scenarios where actions are required on a child window before returning to the parent.
String parent = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
for(String window : allWindows)
}
driver.switchTo().window(parent);
47. How to handle dynamic web elements using Selenium?
contains()
and starts-with()
.
// Using contains to match dynamic ID
WebElement loginBtn = driver.findElement(By.xpath("//button[contains(@id,'login')]"));
// Using wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement dynamicEl = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
48. Write a Selenium script to login to a website with username and password.
driver.get("https://example.com/login");
driver.findElement(By.id("username")).sendKeys("testUser");
driver.findElement(By.id("password")).sendKeys("securePass123");
driver.findElement(By.id("loginButton")).click();
Make sure to replace IDs with actual locators for your application. Optionally, wrap this in a method for reusability.
49. How do you verify the presence of an element?
findElements()
which returns a list—if the list is empty, the element is not present.
List<WebElement> elements = driver.findElements(By.id("dashboard"));
if(elements.size() > 0)
Avoid findElement()
unless you’re certain the element exists, as it throws exceptions if not found.
50. How do you upload a file using Selenium?
file
. No need for AutoIT or Robot unless the upload is via native OS dialog.
WebElement uploadBtn = driver.findElement(By.id("uploadFile"));
uploadBtn.sendKeys("C:\\path\\to\\file.txt");
Always ensure the input field is visible and interactable.
51. How do you take a screenshot using Selenium?
TakesScreenshot
interface. It’s helpful in debugging test failures.
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("screenshot.png"));
Integrate this into your test framework to capture screenshots automatically on test failure.
52. How do you scroll down to a specific element?
WebElement element = driver.findElement(By.id("target"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
This is crucial in infinite scroll or lazy-load scenarios.
53. How do you handle StaleElementReferenceException?
// Wrong: element = driver.findElement(By.id("status"));
// Later: element.click(); → Might throw stale exception
// Correct: Re-find element before use
element = driver.findElement(By.id("status"));
element.click();
Use try-catch or wait-and-retry logic to handle such cases gracefully.
54. How do you wait for an element to be visible?
WebDriverWait
and ExpectedConditions
to wait until the element appears in the DOM and is visible.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("submit")));
This avoids flaky tests caused by timing issues or JavaScript delays.
55. How do you handle alerts/popups in Selenium?
Alert
interface to switch context to a JavaScript alert and perform actions like accept, dismiss, or retrieve text.
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
Make sure you switch back to the main content after handling the alert.
56. How do you handle dropdowns in Selenium?
Select
class provided by Selenium. It allows selecting by visible text, index, or value.
Select dropdown = new Select(driver.findElement(By.id("country")));
dropdown.selectByVisibleText("India");
Verify if the dropdown is a <select>
element, otherwise you’ll need a custom XPath click.
57. Write a script to count the number of links on a webpage.
<a>
tags and simply get the size of the list.
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Total links: " + links.size());
Use this in test scenarios for accessibility or SEO validation.
58. How do you double click on an element using Selenium?
Actions
class enables complex gestures like double click.
Actions action = new Actions(driver);
WebElement btn = driver.findElement(By.id("dblBtn"));
action.doubleClick(btn).perform();
Ensure the element is visible and interactable before performing the action.
59. How do you perform drag-and-drop in Selenium?
Actions
class. Identify source and target, then chain the action.
WebElement source = driver.findElement(By.id("drag"));
WebElement target = driver.findElement(By.id("drop"));
Actions act = new Actions(driver);
act.dragAndDrop(source, target).perform();
60. What’s the difference between driver.close() and driver.quit()?
driver.close()
shuts the current browser window but keeps the WebDriver session alive. driver.quit()
ends the entire session, closing all associated windows. Use quit()
at the end of your test suite for proper resource cleanup.61. What is Page Object Model (POM) in Selenium and why is it useful?
public class LoginPage
}
62. How does Page Factory differ from traditional POM?
@FindBy
annotations. It initializes all elements when the page class is loaded, improving performance and code readability. It’s particularly useful when the DOM is large, and we want quicker access to locators.
PageFactory.initElements(driver, this);
Unlike the traditional approach where elements are defined using driver.findElement()
, Page Factory helps reduce boilerplate code and increases maintainability.
63. What are custom listeners in Selenium and how are they implemented?
ITestListener
or ISuiteListener
.
public class TestListener implements ITestListener
}
Listeners help extend your framework with reporting, retry logic, and advanced debugging capabilities.
64. How do you implement logging in Selenium frameworks?
Log4j
or SLF4J
are commonly integrated with Selenium projects. They allow different logging levels like INFO, DEBUG, ERROR, and WARN to capture detailed runtime behaviour.
Logger log = Logger.getLogger("MyLogger");
log.info("Launching browser");
driver.get("https://example.com");
Proper logging provides transparency and helps reduce effort during failure analysis.
65. What is the role of Maven or Gradle in Selenium automation?
pom.xml
(for Maven) or build.gradle
(for Gradle), you can automatically pull Selenium libraries, plugins, and manage environment configurations seamlessly.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.18.1</version>
</dependency>
They help maintain cleaner projects and enable smooth collaboration among teams.
Tricky Selenium Interview Questions
66. How do you handle dynamic elements in Selenium?
contains()
, or relative locators. Another approach is to rely on surrounding static elements or text.
// Example using contains
driver.findElement(By.xpath("//button[contains(@id,'submit_')]")).click();
Additionally, we can use WebDriverWait to wait for a stable condition like visibility or clickability before interacting with dynamic elements.
67. How do you verify if a file is downloaded successfully using Selenium?
- Set a custom download directory using Chrome/Firefox preferences.
- Use Java to check the file system after triggering download.
File dir = new File("C:/Downloads");
File[] files = dir.listFiles();
boolean found = Arrays.stream(files).anyMatch(f -> f.getName().equals("report.pdf"));
Combining browser config and post-download validation works best in automation pipelines.
68. How do you handle SSL certificate errors in Selenium?
ChromeOptions options = new ChromeOptions();
options.setAcceptInsecureCerts(true);
driver = new ChromeDriver(options);
This is especially useful in QA environments where valid certificates might not be installed.
69. How to take full-page screenshots in Selenium?
TakesScreenshot
captures only the visible viewport. For full-page screenshots:
- Use third-party libraries like AShot or Selenium 4’s dev tools API.
- For Firefox, full-page capture is native in headless mode.
driver = new FirefoxDriver();
driver.get("https://example.com");
File src = ((FirefoxDriver) driver).getFullPageScreenshotAs(OutputType.FILE);
Always validate browser support before using advanced capture methods.
70. How do you scroll to an element in Selenium?
WebElement element = driver.findElement(By.id("footer"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
This ensures visibility before interaction, especially on long pages or lazy-loaded content.
71. What is the difference between driver.close() and driver.quit()?
driver.close()
closes the current browser window that the WebDriver is controlling.driver.quit()
shuts down all browser windows and ends the WebDriver session.
In multi-tab scenarios, close()
is selective, while quit()
ensures full cleanup of memory and resources.
72. How do you perform drag-and-drop using Selenium?
Actions
class provides high-level APIs for complex user gestures like drag-and-drop.
Actions action = new Actions(driver);
action.dragAndDrop(source, target).build().perform();
If native drag-drop fails due to JavaScript handling, JS injection or robot class can be used as fallback.
73. How do you handle browser popups or alerts in Selenium?
Alert
interface.
Alert alert = driver.switchTo().alert();
alert.accept(); // or alert.dismiss();
For unexpected popups, add an explicit wait for ExpectedConditions.alertIsPresent()
.
74. How do you validate broken links on a page using Selenium?
<a>
), then each URL is validated via Java’s HTTP connection.
HttpURLConnection conn = (HttpURLConnection) new URL(link).openConnection();
conn.setRequestMethod("HEAD");
conn.connect();
int respCode = conn.getResponseCode();
If response code is 400 or 500 series, it’s likely a broken link.
75. How do you perform database testing with Selenium?
Connection con = DriverManager.getConnection(dbUrl, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE email='test@example.com'");
Always separate DB validation from UI logic using utility classes.
76. What challenges have you faced with Selenium Grid?
- Node registration errors or mismatched browser versions.
- Session timeouts due to remote driver instability.
- CI/CD integration flakiness with Dockerized Selenium Grid.
A well-maintained hub-node version match and retry logic in framework helps mitigate most problems.
77. How can you run Selenium tests in headless mode?
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
driver = new ChromeDriver(options);
Make sure you handle any UI operations differently as rendering may slightly differ.
78. How do you retry failed tests in TestNG?
IRetryAnalyzer
to retry failed tests automatically.
public class RetryAnalyzer implements IRetryAnalyzer
}
Attach it using @Test(retryAnalyzer = RetryAnalyzer.class)
annotation.
79. What are stale element exceptions and how to avoid them?
StaleElementReferenceException
occurs when the element was present earlier but is now detached from the DOM—commonly due to page refresh or dynamic reload.
Fixes include:
- Re-locate the element before using it again.
- Use explicit waits to wait for visibility before interaction.
80. How do you measure test execution performance in Selenium?
System.nanoTime()
or System.currentTimeMillis()
to capture time before and after steps. For broader metrics, integrate with tools like JMeter, Prometheus, or CI pipeline logs to assess total test duration and step bottlenecks.
long start = System.currentTimeMillis();
// Execute test
long end = System.currentTimeMillis();
System.out.println("Time taken: " + (end - start));
Such insights are essential for improving automation suite efficiency.