Top Selenium Interview Questions & Answers
1. What are Locators in Selenium?
Locators are used to identify web elements on a webpage so that Selenium can interact with them.
- id
- name
- className
- tagName
- linkText
- partialLinkText
- xpath
- cssSelector
2. What is XPath, and what are the types of XPath?
XPath is a locator strategy used to navigate through XML/HTML DOM structure.
Types:
- Absolute XPath → starts from root (
/html/body/...) ❌ not recommended - Relative XPath → flexible and stable (
//input[@id='email']) ✅
XPath is useful for:
- Dynamic elements
- Complex structures
3. What is a page object model?
The Page Object Model (POM) is a design pattern used in test automation that helps you create clean, maintainable, and reusable test code — especially for web applications.
In POM, each web page of your application is represented by a separate class (a “Page Object”), and all the elements (buttons, fields, links, etc.) and actions (clicks, form submissions, etc.) on that page are defined as methods in that class.
Better Code Organization
Keeps UI locators and actions in one place.
Reusability
You can use the same page object in multiple tests.
Easier Maintenance
If a page changes, you update only one file — not all your test scripts.
Improved Readability
Tests become more readable and behave like real-world actions.
4. What is the role of TestNG in Automation Testing?
TestNG is a testing framework that helps organize, execute, and manage automated tests efficiently. It supports features like test grouping, prioritization, parallel execution, and data-driven testing.
It also generates detailed reports and integrates well with tools like Selenium and CI/CD pipelines
5. What are Waits in Selenium?
Waits are used to handle synchronization issues when elements take time to load. Without waits, Selenium may try to interact with elements before they are available, causing failures.
Types:
- Implicit Wait → applies globally
- Explicit Wait → waits for specific condition
- Fluent Wait → customizable
Best practice:
Use Explicit Wait for better control.
6. Difference between Implicit and Explicit Wait
Implicit wait is applied globally and waits for all elements, whereas explicit wait is applied to specific elements based on conditions.
Example:
- Wait until element is clickable
- Wait until element is visible
Explicit wait is preferred because it is more efficient and avoids unnecessary delays.
7. How do you handle dropdowns?
Dropdowns are handled using the Select class in Selenium when the HTML uses <select> tag.
We can select options using:
- Visible text
- Value
- Index
For custom dropdowns (non-select):
We use click and XPath.
8. How do you handle alerts?
Alerts are popups that require user action. Selenium handles them using switchTo().alert().
Operations:
- accept() → click OK
- dismiss() → click Cancel
- getText() → read message
Important:
You must switch to alert before interacting with it.
9. What is StaleElementException?
This exception occurs when the element is no longer attached to the DOM. It usually happens when
- Page refreshes
- DOM updates dynamically
Solution:
- Re-locate the element
- Use explicit wait
10. What is Actions class?
Actions class is used to perform advanced user interactions that cannot be done using simple commands
Examples:
- Mouse hover
- Drag and drop
- Right-click
Used in complex UI scenarios.
11. What is JavaScriptExecutor?
JavaScriptExecutor allows executing JavaScript code inside the browser.
Used when:
- Selenium cannot click element
- Need to scroll page
- Handle hidden elements
Example:
js.executeScript(“window.scrollBy(0,500)”);
12. What is Data-Driven Testing?
In this approach, test data is stored externally (Excel, CSV, JSON), and tests are executed using different data sets.
Benefits:
- Reusability
- Multiple test scenarios
- Better coverage
13. How do you handle failures in automation?
Failures are handled using:
- Retry mechanism
- Screenshot capture
- Logging (Log4j)
- Reports (Extent Reports)
14. What are the different types of navigation commands?
Navigation commands are used to move between pages.
Methods:
- get() → open URL
- navigate().to() → go to URL
- navigate().back() → go back
- navigate().forward() → go forward
- navigate().refresh() → refresh page
15. What is the difference between findElement and findElements?
- findElement → returns a single element, throws exception if not found
- findElements → returns a list of elements, returns empty list if not found
16. How do you handle frames in Selenium?
Frames are handled using switchTo().frame().
Types:
- By index
- By name/id
- By WebElement
17. What is Page Factory in Selenium?
Page Factory is an extension of POM that uses @FindBy annotation to initialize elements.
18. What is Fluent Wait?
Fluent Wait is an advanced wait with customizable timeout and polling interval.
Features:
- Ignore specific exceptions
- Set polling frequency
19. What are common exceptions in Selenium?
Examples:
- NoSuchElementException
- TimeoutException
- StaleElementReferenceException
- ElementNotInteractableException
20. How do you capture screenshots in Selenium?
Using TakesScreenshot interface.
Used for:
- Failure analysis
- Reporting
21. How do you scroll a webpage in Selenium?
Using JavaScriptExecutor.
Examples:
- scrollBy()
- scrollIntoView()
22. How do you handle multiple windows/tabs?
Use getWindowHandles() and switchTo().window()
Steps:
- Store window IDs
- Switch between them
23. How do you implement retry logic in Selenium?
Using TestNG RetryAnalyzer or custom logic to rerun failed tests.
24. How do you design a scalable automation framework?
Use:
- Page Object Model
- Reusable utilities
- Data-driven approach
- Proper logging & reporting
25. What is the difference between Hard Assert and Soft Assert?
- Hard Assert → stops execution on failure
- Soft Assert → continues execution and reports all failures at end
26. How do you integrate Selenium with CI/CD?
Using tools like:
- Jenkins
- GitHub Actions
Steps:
- Trigger tests on build
- Run tests automatically
- Generate reports
27. What is logging in Selenium?
Logging helps track test execution.
Tools:
- Log4j
- SLF4J
28. How do you parameterize tests in TestNG?
Using:
- @DataProvider
- @Test parameters
29. What are best practices in Selenium automation?
- Use stable locators
- Avoid Thread.sleep
- Use Page Object Model (POM)
- Keep tests independent
- Maintain reusable code
30.What is broken link?
A broken link is a hyperlink that does not work or leads to an error page (like 404 Not Found), usually because the target page is missing or invalid.
31. What is the difference between driver.close() and driver.quit()?
- driver.close() → closes current browser window
- driver.quit() → closes all browser windows and ends session
32. What is getText() vs getAttribute()?
- getText() → gets visible text
- getAttribute() → gets attribute value (like value, href)
33. What is a WebElement?
WebElement represents an HTML element in Selenium.
Used to perform actions like:
- click()
- sendKeys()
- getText()
34. What is Maven in Selenium?
Maven is a build automation tool.
Used for:
- Managing dependencies
- Running tests
- Project structure
35. What is Jenkins in Selenium?
Jenkins is a CI/CD tool used to automate test execution.
Used for:
- Scheduling test runs
- Integrating with Git
- Generating reports
36. How do you check if an element is displayed on the page?
Methods:
- isDisplayed()
- isEnabled()
- isSelected()
Used for validation in test cases
37. What is the difference between click() and submit()?
- click(): Clicks any element
- submit(): submit a form
38. How do you handle disabled elements?
Selenium cannot interact directly.
Solution:
- Use JavaScriptExecutor
- Remove disabled attribute
39.What is the difference between getWindowHandle() and getWindowHandles()?
- getWindowHandle(): Returns single window ID
- getWindowHandles(): Returns all window IDs
40.How do you handle dynamic tables?
Steps:
- Locate table
- Use loops for rows and columns
- Use dynamic XPath
41.What is the best wait strategy in Selenium?
Best practice:
- Use Explicit Wait
- Avoid mixing waits
- Avoid Thread.sleep()
42. How do you ensure your automation is stable?
Best practices:
- Use stable locators
- Use waits properly
- Keep tests independent
44 .How do you handle auto-suggestions (like Google search)?
Steps:
- Enter text
- Capture suggestions
- Loop and select
45. What is DOM in Selenium?
DOM (Document Object Model) represents the structure of a webpage.
Used for:
- Locating elements
- Understanding hierarchy
46. How do you handle dynamic elements in Selenium?
Dynamic elements change attributes like id or class at runtime.
Solution:
- Use relative XPath
- Use functions like: contains() ,starts-with()
- Use stable attributes
Example:
//input[contains(@id,’user’)]
47. What will you do if your script fails randomly?
This is called flaky tests.
Approach:
- Add proper waits (Explicit Wait)
- Check synchronization issues
- Verify locators
- Add logging and screenshots
48. How do you handle file upload in Selenium?
If input type=”file”:
Use sendKeys() with file path
If custom upload:
Use AutoIT or Robot class
49. How do you handle file download?
Selenium cannot directly handle OS-level downloads.
Solution:
- Set browser download preferences
- Verify file in download folder
50. How do you validate broken links?
Steps:
- Get all links using findElements(By.tagName(“a”))
- Use HTTP connection
- Check response code
Codes:
- 200 → OK
- 404 → Broken
51. How do you scroll to a specific element?
Using JavaScriptExecutor:
scrollIntoView()
52. How do you handle shadow DOM elements?
Shadow DOM elements are hidden inside shadow root.
Solution:
- Use JavaScriptExecutor
- Access shadowRoot
53. What is the difference between driver.get() and driver.navigate().to()?
get():
- Waits for page load
- Used for initial load
navigate().to():
- Similar but used for navigation
54. How do you run tests in parallel in Selenium?
Using TestNG:
- parallel=”methods” or “classes” in XML
- Use Selenium Grid
55. How do you manage test data?
Using:
- Excel (Apache POI)
- JSON
- DataProvider in TestNG
56. How do you handle stale element exceptions in real projects?
Solution:
- Re-locate element
- Use Explicit Wait
- Avoid storing WebElement for long
57. What challenges did you face in automation?
- Dynamic elements
- Synchronization issues
- Browser compatibility
- Slow execution
58. How do you identify if an element is not clickable?
Check:
- Visibility
- Enabled state
- Overlapping elements
Use:
Explicit Wait → elementToBeClickable
59. How do you debug a failed test case?
Steps:
- Check logs
- Check screenshots
- Re-run test
- Validate locators
- Check environment
60. How do you handle cookies in Selenium?
Methods:
- addCookie()
- getCookies()
- deleteCookie()
61. How do you integrate your framework with CI/CD?
Steps:
- Push code to Git
- Configure Jenkins job
- Trigger build
- Run tests
- Generate report
62. How do you capture screenshots only on failure?
Using:
- TestNG listeners (ITestListener)
- Take screenshot in onTestFailure()
63. What is the difference between Absolute and Relative path?
Absolute:
- Full path
- Not stable
Relative:
- Flexible
- Recommended
64. Your test works in Chrome but fails in Firefox. What will you do?
Possible reasons:
- Different browser behavior
- Locator compatibility issues
- Timing issues
Solution:
- Use cross-browser compatible locators
- Add explicit waits
- Use browser-specific options if needed
65. Element is visible but Selenium is unable to click it. Why?
Possible causes:
- Element overlapped by another element
- Element not clickable yet
- Hidden behind loader
Solution:
- Use Explicit Wait → elementToBeClickable
- Scroll into view
- Use JavaScriptExecutor click as fallback
66. Your XPath is correct but still element is not found. What could be wrong?
Reasons:
- Element inside iframe
- Element inside shadow DOM
- Page not fully loaded
Solution:
- Switch to frame
- Handle shadow root
- Use wait
67. How do you automate a page where elements load after scrolling?
Solution:
- Use JavaScriptExecutor to scroll
- Load elements dynamically
- Use loop until element appears
68. How do you handle a situation where element ID changes every time?
Solution:
- Use contains() or starts-with()
- Use parent-child XPath
- Use other stable attributes
69. Your test passes locally but fails in Jenkins. Why?
Common reasons:
- Environment difference
- Headless mode issues
- Timing issues
Solution:
- Add proper waits
- Check environment configs
- Add logging
70. How do you design your framework for multiple users/logins?
Solution:
- Use DataProvider
- Store test data externally
- Parameterize login
71. How do you handle a calendar/date picker?
Types:
- Simple → sendKeys()
- Complex → click through UI
Steps:
- Open calendar
- Navigate month/year
- Select date
72. How do you handle pagination (multiple pages)?
Solution:
- Loop through pages
- Click “Next” button
- Extract data until last page
73. How do you verify if a file is successfully downloaded?
Steps:
- Set download directory
- Check file existence
- Validate file name
74. What will you do if execution is very slow?
Optimization:
- Run tests in parallel
- Remove Thread.sleep()
- Use headless mode
- Optimize locators
75. How do you handle dependency between test cases?
Solution:
- Avoid dependency (best practice)
- Use TestNG dependsOnMethods if needed
76. How do you test a login page with multiple invalid inputs?
Approach:
- Use DataProvider
- Pass multiple datasets
Example:
- Invalid username
- Invalid password
- Empty fields
77. What if application UI changes frequently?
Solution:
- Use POM design
- Centralize locators
- Use stable attributes
78. How do you validate error messages?
Steps:
- Capture element text
- Compare with expected
Use:
assertEquals()
79. What are the test types supported by Selenium?
For testing web-based applications, Selenium can be used.
The test types supported by Selenium are:
- Functional testing: It verifies if each function of a software application performs in accordance with specific requirements. This testing primarily involves black-box testing, and it is not concerned with the source code of the application.
- Regression testing: It is nothing but a full or partial selection of the already executed test cases to be re-executed to ensure that the existing functionalities work fine.
80. In Selenium, what are breakpoints and start points?
Breakpoints: Breakpoints are used to stall the execution of the test. The execution will stop whenever a breakpoint is implemented, and this will help us check whether the code is working properly or not.
Start points: Start points are the points from where the execution should begin. Start points can be used when we want to run the test script from the middle of the code or after a breakpoint.
81. What is DOM inspection?
Inspecting webpage structure using browser DevTools.
Used for:
- Locators
- XPath
- CSS selectors
82. What are the latest features in Selenium 4?
Features:
- Relative locators
- Selenium Manager
- Improved Grid
- Better DevTools support
- New window/tab handling
83. What is smoke suite in automation?
Small set of critical test cases executed after every build.
Purpose:
- Verify build stability quickly.
84. What is a locator strategy hierarchy?
Preferred locator order:
- ID
- Name
- CSS Selector
- XPath
Because IDs are fastest and most stable.
85. What are flaky tests?
Tests that:
- Pass sometimes
- Fail sometimes
Reasons:
- Timing issues
- Dynamic elements
- Environment instability
86. How do you reduce flaky tests?
- Use explicit waits
- Stable locators
- Retry mechanism
- Proper synchronization
- Independent tests
87. What metrics do you track in automation?
- Pass/fail percentage
- Automation coverage
- Execution time
- Defect leakage
- Stability rate
88. What reporting tools are used with Selenium?
Popular reporting tools:
- Extent Reports
- Allure Reports
- TestNG Reports
89. What is Extent Report?
Advanced HTML reporting library used for:
- Logs
- Screenshots
- Execution reports
90. What is the difference between verification and validation?
| Verification | Validation |
| Checks whether product is built correctly | Checks whether correct product is built |
| Process-oriented | Product-oriented |
91. What is ThreadLocal in Selenium?
Used in parallel execution to maintain separate WebDriver instances per thread.
Example use:
- Parallel test execution in TestNG
92. How do you automate OTP-based login?
Usually OTP is not automated directly.
Approaches:
- Disable OTP in test environment
- Fetch OTP from database/API/email
- Use static OTP in lower environments
93. What if developer changes locator frequently?
- Use relative XPath/CSS
- Coordinate with developers
- Add stable attributes like data-testid
94. How do you validate large datasets in UI?
- Database comparison
- API validation
- Dynamic table handling
95. What if test data is unavailable?
Approaches:
- Generate test data dynamically
- Use APIs/database
- Mock services
96. How do you manage secrets/passwords in framework?
Never hardcode credentials.
Use:
- Environment variables
- Vault tools
- Encrypted config
97. How do you validate images on webpage?
Check:
- Image displayed
- HTTP response
- Natural width > 0
98. How do you handle hidden elements?
Using:
- JavaScriptExecutor
- Actions class
- Wait until visible
99.What will you do if there are no unique locators?
Use:
- Relative XPath
- Parent-child relationship
- CSS hierarchy
- Multiple attributes
100. What is a Keyword-Driven Framework?
A Keyword-Driven Framework is an automation framework where test actions are represented using predefined keywords like Click, Type, and Login.
The test data, locators, and actions are maintained separately from the test scripts, making the framework more reusable, maintainable, and easy to understand.