Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Most Asked Selenium Interview Questions
3.
Selenium Interview Questions for Freshers
3.1.
1. What is Selenium?
3.2.
2. What are the advantages of automation testing?
3.3.
3. What are the different components of Selenium?
3.4.
4. What are the limitations of Selenium?
3.5.
5. What is the testing automation of different programming languages, browsers and operating systems that Selenium supports?
3.6.
6. Describe major upgrades/changes in different Selenium versions.
3.7.
7. What is Selenese?
3.8.
8. Explain different ways of locating a web element in Selenium.
3.9.
9. Explain the policy of same-origin and how Selenium handles it.
3.10.
10. What do you mean by the assertion in Selenium?
3.11.
11. Explain the difference between assert and verify commands?
3.12.
12. What is XPath in Selenium?
3.13.
13. What is the difference between “/” and “//” in XPath?
3.14.
14. What are the different annotations used in Selenium?
3.15.
15. What are the WebDriver-supported Mobile Testing Drivers?
3.16.
16. How do you handle dropdowns in Selenium?
3.17.
17. What is an implicit wait in Selenium?
3.18.
18. How do you switch to a new window or tab in Selenium?
3.19.
19. What is the difference between getWindowHandle() and getWindowHandles() in Selenium?
3.20.
20. How do you handle alerts in Selenium?
4.
Selenium Interview Questions for Experienced
4.1.
21. What is the difference between "type keys" and "type" commands?
4.2.
22. What's the difference between findElement() and findElements()?
4.3.
23. What is Selenium Grid?
4.4.
24. In Selenium WebDriver, how do we launch different browsers?
4.5.
25. What kinds of waits are there in WebDriver?
4.6.
26. How to Enter Text into a Textbox Using Selenium?
4.7.
27. How can we obtain the text of a web element?
4.8.
28. What is the difference between the driver.close() and driver.quit commands?
4.9.
29. How can we deal with pop-ups based on Windows?
4.10.
30. What is TestNG, and how is it superior to Junit?
4.11.
31. What exactly is an Object Repository? In Selenium, how can we construct an Object Repository?
4.12.
32. What types of frameworks in Selenium are there?
4.13.
33. What types of tests does Selenium support?
4.14.
34. In the Selenium IDE, how can you debug the tests?
4.15.
30. What are regular expressions, and how can you use them in Selenium?
4.16.
35. What are steps for troubleshooting tests using Selenium IDE?
4.17.
36. What is the Actions class in Selenium?
4.18.
37. What is the meaning of the testng.xml file?
4.19.
38. What are the strategies to improve the performance of Selenium tests?
4.20.
39. How do we handle dynamic web elements in Selenium?
4.21.
40. How do we handle AJAX calls in Selenium?
4.22.
41. How do we perform drag-and-drop operations in Selenium?
4.23.
42. What do you mean by the Page Factory in Selenium, and how can we use it?
4.24.
43. How do we handle the SSL certificate errors in Selenium?
4.25.
44. How do we manage cookies in Selenium?
4.26.
45. How can we take screenshots in Selenium?
4.27.
46. What do you mean by DesiredCapabilities in Selenium?
4.28.
47. What is Selenium Grid, and when would we use it?
4.29.
48. How can we upload files in Selenium?
4.30.
49. How can we handle StaleElementReferenceException?
4.31.
50. What is the role of JavaScriptExecutor in Selenium, and when would you use it?
4.32.
51. How can we handle tests that need to verify email content in Selenium?
4.33.
52. How do we handle dynamic waits for elements that load after AJAX calls?
5.
Selenium WebDriver Interview Questions
5.1.
53. What is the recommended API for testing databases in conjunction with Selenium WebDriver?
5.2.
54. To click on a hyperlink, how would you use Selenium WebDriver?
5.3.
55. How does one use Selenium WebDriver to submit a form?
5.4.
56. How does one enter text into the text box using Selenium Webdriver?
5.5.
57. How does one clear the text from text box in  Selenium WebDriver?
5.6.
58. List different types of frameworks and connections using the Robot Framework of Selenium.
5.7.
59. Is it possible to Windows-based pop-up inside Selenium?
5.8.
60. What are the types of waits supported by WebDriver?
5.9.
61. Name the types of navigation commands in Selenium WebDriver.
5.10.
62. How would you write the code to launch the Internet Explorer browser in WebDriver? And then navigate it to the official website of Coding Ninjas.
5.11.
63. What are the advantages of TestNG?
5.12.
64. What is Hub in Selenium Grid?
5.13.
65. In Selenium we have a node in Selenium Grid, what is that node?
5.14.
66. What mouse functions can be performed using Selenium?
5.15.
67. What is the code to double-click an element on the webpage?
5.16.
68. In a webpage, how can we be sure that the element is enabled for the interaction?
5.17.
69. How does one get the current page URL in Selenium?
5.18.
70. How can one retrieve the title of the webpage in Selenium?
6.
Selenium Tricky Interview Questions
6.1.
71. How do we handle a scenario where an element's ID changes dynamically on each page load?
6.2.
72. How can we handle testing of an application that uses Web Components extensively?
6.3.
73. What would we do if an element is loading too slowly in Selenium?
6.4.
74. How can we handle date pickers in Selenium WebDriver?
6.5.
75. How would you test an infinite scroll page using Selenium?
6.6.
76. How can we handle hidden elements in Selenium?
6.7.
77. How can we handle a dropdown that's not a standard SELECT element but a custom JavaScript implementation?
6.8.
78. How do we handle elements with the same attributes and no unique identifiers in Selenium?
6.9.
79. How can we handle a scenario where the application uses shadow DOM extensively?
6.10.
80. How can we check if a text is present on a web page using Selenium?
6.11.
81. How can we test an application that uses WebSockets for real-time updates?
6.12.
82. How can we test file downloads in a headless browser environment?
6.13.
83. How can we handle CAPTCHA in Selenium?
6.14.
84. How would we handle testing of an application that uses client-side encryption for form submissions?
6.15.
85. How can we test responsive design effectively using Selenium?
7.
Selenium MCQ Questions
7.1.
1. What does selenium mean?
7.2.
2. What is the purpose of TestNG?
7.3.
3. Choose the programming languages that are commonly used with Selenium?
7.4.
4. Choose the command that can be used for navigating the specific URL?
7.5.
5. How the screenshot can be taken in the Selenium web driver?
7.6.
6. How the events in the Selenium web driver can be handled?
7.7.
7. How the Selenium web driver can refresh the current web page?
7.8.
8. How the "enter" key on a keyboard can be pressed by using the command in the selenium web driver?
7.9.
9. How can we switch to the i-frame element in selenium web driver?
7.10.
10. What does the "executeScript" method use for?
8.
Frequently Asked Questions
8.1.
Q. What are the 4 major components of Selenium WebDriver?
8.2.
Q. What are the 3 parts of Selenium?
8.3.
Q. Why do we use WebDriver in Selenium?
8.4.
Q. What is Selenium used for in QA testing?
8.5.
Q. What is POM Selenium?
9.
Conclusion
Last Updated: Aug 31, 2024
Medium

Selenium Interview Questions

Introduction

Selenium is a free and open-source automation framework. Its primary use is validating web-based applications over several browsers and devices. It is also capable of automating web-based administration operations. It is the most popular web automation framework.

We have provided a curated list of the most frequently asked Selenium interview questions and answers. This article will provide you with valuable tips to help you succeed in your next Interview. Let’s explore the most asked Selenium interview questions and answers which are categorized into different categories i.e. 

  • Most Asked Selenium Interview Questions
  • Selenium Interview Questions for Freshers
  • Selenium Interview Questions for Experienced
  • Selenium WebDriver Interview Questions
  • Selenium Tricky Interview Questions
  • Selenium MCQ Questions
Selenium Interview Questions

We have provided a curated list of the most frequently asked Selenium interview questions and answers. This article will provide you with valuable tips to help you succeed in your next Interview. Let’s explore the most asked Selenium interview questions and answers which are categorized into three categories i.e. Selenium Interview Questions for Freshers and experienced.

Most Asked Selenium Interview Questions

  1. What is Selenium?
  2. What are the advantages of automation testing?
  3. What are the different components of Selenium?
  4. What are the limitations of Selenium?
  5. What is Selenese?
  6. Explain different ways of locating a web element in Selenium.
  7. What do you mean by the assertion in Selenium?
  8. What is XPath in Selenium?
  9. What is the difference between “/” and “//” in XPath?
  10. What are the different annotations used in Selenium?

Selenium Interview Questions for Freshers

1. What is Selenium?

Selenium is an automated testing framework that is free and open-sourced, which allows testers to write and execute automated tests for web applications across various browsers and platforms. It provides a suite of software tools that cater to different testing needs, including Selenium IDE, Selenium Remote Control, WebDriver, and Selenium Grid. Selenium supports multiple programming languages and can be used to validate the functionality of web applications. Overall, Selenium is a widely used tool for web application testing due to its flexibility, compatibility, and ease of use. 

2. What are the advantages of automation testing?

The primary advantages of automation testing include the followings:
→ It covers both functional and regression testing of web applications.
→ Because automated execution of test cases is faster than manual execution, automated testing enhances coverage.
→ It helps in the parallel execution of different testing tasks.
→ It improves accuracy by eliminating the possibility of human error.
→ It enables you to save both time and money.

3. What are the different components of Selenium?

Selenium is a well-known automated testing framework. It's a playback tool that allows you to perform functional testing without writing test scripts. Selenium is a web UI-based automation testing package that is open-source. 
It has four major components:
→ Selenium Integrated Development Environment (IDE)
→ Selenium Remote Control
→ WebDriver
→ Selenium Grid

4. What are the limitations of Selenium?

The limitations of Selenium are as follows:
→ It only works for web-based applications; it cannot test Windows or Android applications.
→ Selenium is dependent on third-party applications for reporting purposes.
→ It can not handle captcha and barcodes.
→ Selenium has issues with handling frames and pop-up windows.
 

5. What is the testing automation of different programming languages, browsers and operating systems that Selenium supports?

The Selenium framework supports many systems, browsers and languages. 
→ Programming Languages: JavaScript (Node. js), Java, Ruby, Python, Kotlin, and C#.
→ Operating systems: Linux, Microsoft Windows, macOS
→ Browsers: Chrome, Firefox, Microsoft Edge, Opera Browser, Safari.

Click on the following link to read further: Javascript Interview Questions and Answers

6. Describe major upgrades/changes in different Selenium versions.

Following are the significant changes in different versions of the Selenium framework:

Selenium 1.0- It was the first release of the Selenium framework, which included three tools, namely, Selenium IDE, Selenium RC, and Selenium Grid.
Selenium 2.0- Selenium WebDriver has taken the position of Selenium Remote Control. 
- Selenium Remote Control has been deprecated and is now part of the legacy package.
Selenium 3.0- Major fixes and improvements to Selenium 2.0. 
- Depreciation of Selenium Core, the WebDriver completely replaced Selenium core due to its high popularity.
Selenium 4.0- It strictly follows W3C standard protocol. 
- It deprecated support for Opera Browser and PhantomJS. 
- It has optimized Selenium Grid and improved IDE.

7. What is Selenese?

The commands used to execute Selenium tests are commonly known as "Selenese." We use these Selenese commands to test web applications. One can verify the existence of UI elements by looking at their HTML tags. Selenium uses “commands” to determine what actions or activities to do.
Example: open(URL), is used to open the URL in the specified browser.

8. Explain different ways of locating a web element in Selenium.

In Selenium, Locators are used to identify and locate web items. In the context of a web application, locators define a unique target position for a web element. Different type of locators used in Selenium are as follows:
ID: find_element_by_id
Class name: find_element_by_class_name
Xpath: find_element_by_xpath
Link text: find_element_by_link_text
Attribute name: find_element_by_name
Partial link text: find_element_by_partial_link_text
HTML tag name: find_element_by_tag_nameb

9. Explain the policy of same-origin and how Selenium handles it.

The Same Origin policy is a security feature. It allows a web browser to run scripts from one webpage to access the contents of another webpage till both pages have the exact origin. The origin is the combination of the URL scheme, hostname, and port number. This policy prevents sensitive information on one website from being compromised by another website.

10. What do you mean by the assertion in Selenium?

Asserts in Selenium are application validations or checkpoints. Assertions assert confidently that the application's behaviour is as expected. ‘Asserts’ in Selenium validate test cases, as the name implies. They assist testers in determining if tests have passed or failed. "assert," "verify," and "waitFor" are the three kinds of assertions. 

11. Explain the difference between assert and verify commands?

Assert: The assert command determines whether or not the provided condition is true. If the condition is true, the programme control will proceed to the next testing phase. Execution will halt if the condition is false.
→ Verify: The verify command also determines whether or not the provided condition is true. It does not halt programme execution, i.e., if there is a failure during verification, the programme will continue to run, and all test phases will be complete.

12. What is XPath in Selenium?

The term XPath is an alternative name to XML Path. It's an XML querying language. It's a crucial method for locating Selenium's elements. XPath allows testers to browse through any document's XML structure, and it works on both HTML and XML documents. 
There are two different types of XPath in Selenium.
1. Absolute Path (Complete path to the element)
2. Relative Path (Starts with a double slash which signifies a break in the absolute path)

Read about,  Wordpress Interview Questions

13. What is the difference between “/” and “//” in XPath?

Single Slash “/” - The single slash generates an Xpath with an absolute path, which means the XPath will start selection from the document node/start node.
→ Double Slash "//" - The double slash constructs an Xpath with a relative path. This means the XPath can start selection from anywhere on the page.

14. What are the different annotations used in Selenium?

JUnit Annotations- Test, BeforeClass, AfterClass, Before, After, Ignore, RunWith
→ TestNG Annotations- BeforeSuite, BeforeTest, BeforeClass, BeforeMethod, Test, AfterMethod, AfterClass, AfterTest.

15. What are the WebDriver-supported Mobile Testing Drivers?

Various WebDriver for mobile testing by Selenium are:
→AndroidDriver
→IphoneDriver
→OperaMobileDriver

16. How do you handle dropdowns in Selenium?

Dropdowns can be handled using the Select class in Selenium. For example:

Select dropdown = new Select(driver.findElement(By.id("dropdownId"))); 
dropdown.selectByVisibleText("Option Text");

17. What is an implicit wait in Selenium?

An implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element (or elements) not immediately available. For example:

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

18. How do you switch to a new window or tab in Selenium?

To switch to a new window or tab:

Set<String> windowHandles = driver.getWindowHandles(); 
for(String handle: windowHandles) {     
	driver.switchTo().window(handle); 
}

19. What is the difference between getWindowHandle() and getWindowHandles() in Selenium?

The difference between getWindowHandle() and getWindowHandles() in Selenium are:

  • getWindowHandle(): This method returns a string representing the unique identifier of the current browser window.
  • getWindowHandles(): This method returns a set of strings representing the unique identifiers for all the open browser windows.

20. How do you handle alerts in Selenium?

Alerts can be handled using the Alert interface:

Alert alert = driver.switchTo().alert(); 
// To accept the alert
alert.accept();   

// To dismiss the alert
alert.dismiss(); 

Selenium Interview Questions for Experienced

21. What is the difference between "type keys" and "type" commands?

Type: When you need to enter text into an input field, type is used in the same way as a human enters a value. 
→ Type Keys: typeKeys simulates each keystroke. When a page performs an action while you enter, such as autosuggest in search fields, it uses this tag.

22. What's the difference between findElement() and findElements()?

findElement(): Using the provided "locating technique", this function locates the first element on the current page. It gives back a single WebElement.
→ findElements(): This function uses the provided "locating technique" to locate all of the elements on the current page. It gives you a list of web elements.

23. What is Selenium Grid?

Selenium Grid allows you to simultaneously distribute your tests across numerous machines. As a result, using the same test script, you can run tests on Internet Explorer on Windows and Safari on Mac. It shortens test execution time and gives immediate feedback.

24. In Selenium WebDriver, how do we launch different browsers?

We must first build an instance of that browser's driver as shown below:
WebDriver driver = new ChromeDriver();
In this scenario, "WebDriver" is an interface, and we're establishing a reference variable "driver" of type WebDriver, which instantiates the "ChromeDriver" class.

25. What kinds of waits are there in WebDriver?

In WebDriver, there are two sorts of waits:

Implicit Wait: Implicit waits establish a default waiting period (say, 30 seconds) between each successive test step/command across the whole test script. As a result, the next test step would not run until 30 seconds since the previous test step/command executes.

Explicit Wait: An explicit wait halts the execution until a specific condition or the maximum time has elapsed. Unlike implicit waits, explicit waits apply to only one instance.

26. How to Enter Text into a Textbox Using Selenium?

To enter the string into the textbox, the user can use sendKeys("Some strings here").|
Syntax:
WebElement emailid = drv.findElement(By.id(“mailbox”));
emailid.sendKeys(“email@example.com”);

27. How can we obtain the text of a web element?

The get command accesses the inner text of a web element. The command takes no parameters and returns a string value. It is also one of the most commonly used commands for verifying messages, labels, errors, and other information presented on web pages.
Syntax:
String Sometext = driver.findElement(By.id(“Example”)).getText();

28. What is the difference between the driver.close() and driver.quit commands?

The close() method of the WebDriver shuts the web browser window that the user is currently working on or the window that the WebDriver is currently accessing. The command does not accept any parameters and does not return any value.
Unlike the close() method, the quit() method shuts all windows that the programme has opened. Like the close() method, the command does not require any parameters and does not return any value.

29. How can we deal with pop-ups based on Windows?

Selenium is an automation testing tool that only enables web application testing; it does not support testing of Windows applications. However, while Selenium cannot alleviate the matter on its own, it is overcome with the support of a third party. Along with Selenium, there are various third-party solutions available for managing window-based pop-ups, such as AutoIT, Robot class, and so on.

30. What is TestNG, and how is it superior to Junit?

TestNG is a sophisticated framework designed to benefit developers and testers. With the introduction of frameworks, JUnit gained massive popularity among Java applications, Java developers, and Java testers, significantly enhancing code quality. Despite its ease of use and simplicity, JUnit has restrictions that necessitate the inclusion of TestNG. TestNG is an open-source framework that is freely available for download under the Apache Software License.
TestNG with WebDriver provides an efficient and effective test result format that is communicated with stakeholders to provide a snapshot of the product's/health/ application's hence overcoming the disadvantage of WebDriver's inability to generate test results.

There are several advantages of using TestNG over JUnit. Among them are:
a. Advance and simple annotations included.
b. It is possible to develop execution patterns.
c. Execution of test scripts at the same time.
d. It is possible to define test case dependencies.

31. What exactly is an Object Repository? In Selenium, how can we construct an Object Repository?

The phrase "Object Repository" refers to a collection of web elements belonging to the Application Under Test (AUT) as well as their locator values. As a result, the location value may be fetched from the Object Repository whenever the script uses the element. Instead of hardcoding locators into scripts, Object Repository stores them in a centralised location.

An excel sheet saves the object in Selenium, which can then be populated within the script as needed.

32. What types of frameworks in Selenium are there?

Some of the important frameworks are as follows:

Data-driven frameworkThis type of test data is created from external files such as Excel, CSV, XML, etc. The data about the test cases rely on input and verification values kept via variables.
Framework based on keywordsThe data tables and keywords are created separately from the automated test cases. The functionality of the test scenarios is documented step by step in the table in this framework.
Module-based testing frameworkThe application under test is divided into isolated and logical modules. Each module has its own set of test scripts. These scripts are then combined as a whole.
Behavior-driven testing frameworkThe test scripts are constructed in such a way that automation is performed on the functionality or features to assure readability, understanding, and reliability to either business experts, developers, or other testers.
Hybrid testing frameworkA Hybrid testing framework is a combination of more than one of the frameworks mentioned above that leverage the benefits of each.

33. What types of tests does Selenium support?

Selenium enables both regression and functional testing.
Regression testing is the re-execution of a full or partial set of previously executed test cases to confirm that current functionality continues to function correctly. 
The steps are as follows:
a. Re-testing: All of the tests in the existing test suite are rerun. It turns out to be quite costly and time-consuming.
b. Regression test selection: Tests are of three types: feature tests, integration tests, and end-to-end tests. Some of the test selections occur in this step.
c. Prioritisation of test cases: Test cases are prioritized based on their business effectiveness and essential functionalities.

Functional testing entails verifying that every application function meets the needed specifications. The steps involved are as follows:
a. Determine the test input.
b. Calculate the test result.
c. Carry out the test.
d. Contrast the test result with the actual result.

34. In the Selenium IDE, how can you debug the tests?

The steps to debug the tests in Selenium IDE are:
a. We must first place breakpoints to debug and execute the test step by step.
b. Run the test case afterward.
c. Following that, the execution terminates at the breakpoint.
d. You can continue the execution of all the commands consecutively by clicking the Run button.

30. What are regular expressions, and how can you use them in Selenium?

Regular expressions are specific text strings that represent search patterns. Regexp is a keyword that can be used as a prefix to treat a text as a regular expression in Selenium.
Example: 

driver.find_element_by_xpath("//input[contains(@name,'somestring')]")

 

  • It will look for the input tag that has the 'name' property and include the text 'somestring'.
  • Here the method “starts-with()” implies that the string begins with the provided text

35. What are steps for troubleshooting tests using Selenium IDE?

Some steps for troubleshooting tests in Selenium IDE are:

  1. Identify the problem: The first step is to identify and understand the problem.
  2. Check the test case: Once the problem is identified, the second step would be to check the test case itself. One needs to make sure that test cases are written correctly
  3. Check the environment: One needs to make sure the environment they working in set up correctly as it can have an impact on the test result.

36. What is the Actions class in Selenium?

The Actions class is defined in the Selenium Python bindings which are used for automating web browsers. It allows us to perform actions on web elements, like moving the mouse over an element or sending keys to it.

37. What is the meaning of the testng.xml file?

testng.xml is a TestNG configuration file that is used to organize and execute test suites and cases. It helps us to set up for the test executor order, parallel execution, and test data and enables users to understand which methods or classes should be used or not used in a test run.

38. What are the strategies to improve the performance of Selenium tests?

There are some strategies for improving the performance of Selenium tests:

  • We can use explicit waits instead of Thread.sleep()
  • We can implement parallel execution using TestNG or JUnit
  • We can use headless browser testing for faster execution
  • We can minimize browser window for quicker rendering
  • We can use the Page Object Model(POM) for better maintainability
  • We can implement proper test data management
  • We can use appropriate locator strategies (prefer ID and CSS over XPath)
  • We can regularly update Selenium and browser drivers

39. How do we handle dynamic web elements in Selenium?

We can handle the dynamic web elements using various strategies:

  • We can use partial locators( contains(), starts-with(), and ends-with()) in the XPath.
  • We can use WebDriverWait for explicit waits
  • We can use JavaScript Executor to find elements
  • We can implement the custom expected conditions

40. How do we handle AJAX calls in Selenium?

We can handle the AJAX calls using explicit waits with ExpectedConditions:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("elementId")));

41. How do we perform drag-and-drop operations in Selenium?

We can perform the drag and drop operation by using the Actions class. For example:

Actions actions = new Actions(driver);
WebElement source = driver.findElement(By.id("sourceElementId"));
WebElement target = driver.findElement(By.id("targetElementId"));
actions.dragAndDrop(source, target).perform();

42. What do you mean by the Page Factory in Selenium, and how can we use it?

Page Factory is a class provided by Selenium WebDriver. This class supports Page Object Design patterns. This is used to initialize web elements declared in Page Objects. For example:

public class LoginPage {
    @FindBy(id = "username")
    private WebElement usernameInput;
    public LoginPage(WebDriver driver) {
        PageFactory.initElements(driver, this);
    }
}

43. How do we handle the SSL certificate errors in Selenium?

We can handle SSL certificate errors in Selenium for Chrome browser using the method setAcceptInsecureCerts(). For example:

ChromeOptions options = new ChromeOptions();
options.setAcceptInsecureCerts(true);
WebDriver driver = new ChromeDriver(options);

 

This similar approach we can follow for other browsers.

44. How do we manage cookies in Selenium?

We can manage cookies using several methods. Selenium provides methods to manage cookies:

  • Add a cookie: driver.manage().addCookie(new Cookie("key", "value"));
  • Delete a cookie: driver.manage().deleteCookieNamed("key");
  • Get a cookie: Cookie cookie = driver.manage().getCookieNamed("key");
  • Delete all cookies: driver.manage().deleteAllCookies();

45. How can we take screenshots in Selenium?

We can take a screenshot in Selenium using the method getScreenshotAs(). For example:

TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("./screenshot.png"));

46. What do you mean by DesiredCapabilities in Selenium?

DesiredCapabilities is used to set properties for WebDriver. The properties we can set such as browser name, version, platform, etc. It helps configure the test environment before initiating a session. It's particularly useful in Selenium Grid to define capabilities for different nodes.

47. What is Selenium Grid, and when would we use it?

Selenium Grid allows running tests in parallel across different machines and browsers. We can use it for various purposes like:

  • Cross-browser testing
  • To reduce execution time by parallel testing
  • To test on different OS/browser combinations

48. How can we upload files in Selenium?

We can upload files in Selenium using the sendKeys() method. Using this method we can pass the file path to the file input element. For example:

WebElement uploadElement = driver.findElement(By.id("uploadElementId"));
uploadElement.sendKeys("C:\\path\\to\\file.txt");

49. How can we handle StaleElementReferenceException?

We can handle the StaleElementReferenceException by:

  • Re-locating the element before interacting with it
  • Using WebDriverWait with ExpectedConditions
  • Implementing custom retry logic
  • Using try-catch blocks to catch and handle the exception

50. What is the role of JavaScriptExecutor in Selenium, and when would you use it?

JavaScriptExecutor is an interface that allows you to execute JavaScript code directly within the context of the browser. It is used when certain actions cannot be performed using standard WebDriver methods or when you need to interact with elements that are not directly accessible through WebDriver.

Example of scrolling to an element:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);", element);

51. How can we handle tests that need to verify email content in Selenium?

Testing email content requires integration with email APIs or services. We can follow these steps:

  1. We need to set up a test email account or we can use a temporary email service.
  2. We can perform the action that triggers the email (e.g., user registration).
  3. We can use JavaMail API or a REST API to fetch the latest email.
  4. We can parse the email content (or we can use libraries like JSoup for HTML emails).
  5. We need to assert the email content.

52. How do we handle dynamic waits for elements that load after AJAX calls?

We can handle the dynamic waits for AJAX-loaded elements using WebDriverWait with custom ExpectedConditions. For example:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

wait.until(new ExpectedCondition<Boolean>() {
    public Boolean apply(WebDriver driver) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        return (Boolean) js.executeScript("return jQuery.active == 0");
    }
});

Selenium WebDriver Interview Questions

53. What is the recommended API for testing databases in conjunction with Selenium WebDriver?

Selenium WebDriver is one of the tools used for automating web browsers though its not designed for database testing. So to test databases, we need a database testing tool that can connect to the database and help perform a number of operations like running SQL queries and getting the results. Some examples of data testing are DBUnit, JDBC, etc.

54. To click on a hyperlink, how would you use Selenium WebDriver?

We use the “click” method on the element to simulate a click on the hyperlink

// Import necessary packages
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

// Create a new instance of the Chrome driver
WebDriver driver = new ChromeDriver();

// Navigate to the web page containing the hyperlink
driver.get("https://example.com");

// Find the hyperlink element by ID
WebElement myLink = driver.findElement(By.id("myLink"));

// Click on the hyperlink
myLink.click();
You can also try this code with Online Python Compiler
Run Code

55. How does one use Selenium WebDriver to submit a form?

We use the “get()” method to load the webpage containing the form. Then locate the form element on the web page using one of the locators. Then find the input fields of the form and enter the necessary value using the “sendKeys()” method. And finally, use the “submit()” method to submit the form once all the entries are filled in. Below code snippet gives an example of how the code looks like to submit a from using Selenium Webdriver.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

// Create a new instance of the Chrome driver
WebDriver driver = new ChromeDriver();

// Load the web page containing the form
driver.get("https://example.com/my-form");

// Locate the form element on the web page
WebElement myForm = driver.findElement(By.id("my-form"));

// Find the input fields of the form and enter values
WebElement firstNameField = myForm.findElement(By.id("first-name"));
firstNameField.sendKeys("John");
WebElement lastNameField = myForm.findElement(By.id("last-name"));
lastNameField.sendKeys("Doe");

// Submit the form
myForm.submit();

 

56. How does one enter text into the text box using Selenium Webdriver?

We use the method “sendKeys()” to enter the text in the text box.

textBox.sendKeys("Hello, World!");

57. How does one clear the text from text box in  Selenium WebDriver?

We use the “clear()” method to clear the text. Below code snippet demonstrates how its done.

WebElement textBox = driver.findElement(By.id("my-text-box"));
textBox.clear();


Read more about: Html interview questions

58. List different types of frameworks and connections using the Robot Framework of Selenium.

  • Keyword-Driven Testing Framework
  • Library Architecture Testing Framework
  • Data-Driven Testing Framework
  • Module-Based Testing Framework
  • Hybrid Testing Framework

59. Is it possible to Windows-based pop-up inside Selenium?

Selenium doesn't support Windows-based pop-ups since Selenium is an automated tool that is built specifically for web application-based testing. However many 3rd party tools support this like Robot Class. 

60. What are the types of waits supported by WebDriver?

There are 3 types of waits that are supported by WebDriver namely:

  1. Implicit Wait: It gives the command to Selenium to wait for a specific amount of time before giving a “No such element” exception
  2. Explicit Wait: It is used to let the WebDriver wait for specific conditions before throwing an “ElementNotVisibleException” exception
  3. Fluent Wait: It is used when one wants to let the WebDriver wait for specific conditions, as well as the frequency by the condition we want to check before it throws an “ElementNotVisibleException”.

61. Name the types of navigation commands in Selenium WebDriver.

driver.navigate().to("https://www.codingninjas.com/") - it helps us navigate the provided URL 

driver.navigate().refresh() - it helps us to refresh the current page

driver.navigate().forward() - it is similar to clicking on the forward button on any browser

driver.navigate().back() - it is similar to clicking on the back button on any browser

62. How would you write the code to launch the Internet Explorer browser in WebDriver? And then navigate it to the official website of Coding Ninjas.

The code we can use to navigate to the Coding Ninjas website through Internet Explorer is as follows:

WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.codingninjas.com");

63. What are the advantages of TestNG?

  • It provides a way for parallel execution.
  • It helps us in checking the actual and the expected test results by providing us with different exertions.
  • We can assign priority to the test methods.
  • We can use it to define the dependent of the test methods over other methods using TestNG

64. What is Hub in Selenium Grid?

Selenium Grid helps us in distributed testing. Using the Selenium Grid, we can run test scripts on multiple machines from different browsers. A Hub is kind of a server or the central point in the Selenium Grid which controls the number of text executions on different machines.

65. In Selenium we have a node in Selenium Grid, what is that node?

A node is a machine that is used in Selenium as an instance which is further connected to the Selenium Grid Hub and runs the test scripts. Although unlike hubs, selenium lattice can have multiple nodes.

66. What mouse functions can be performed using Selenium?

The mouse functions that can be performed are:

  • mouseMove(WebElement element, long xOffset, long yOffset)
  • click(WebElement element)
  • mouseUp(WebElement element)
  • mouseMove(WebElement element, long xOffset, long yOffset)
  • mouseDown(WebElement element)
  • mouseMove(WebElement element)
  • doubleClick(WebElement element)

67. What is the code to double-click an element on the webpage?

The following code describes how one can double-click an element from Selenium:

WebElement element = driver.findElement(By.xpath("yourXpathHere"));
Actions actions = new Actions(driver);
actions.doubleClick(element).perform();

 

Using Xpath, we locate the element that we are double-clicking on, then created an instance of the Actions class. Then we use doubleClick() method and pass the element in the method and finally use the perform() function to execute the code.

68. In a webpage, how can we be sure that the element is enabled for the interaction?

To know if an element is enabled for interaction on the webpage, we write this code:

WebElement element = driver.findElement(By.xpath("path_of_the_element"));
if(element.isEnabled()) {
    System.out.println("Element is enabled for interaction.");
} else {
    System.out.println("Element is disabled for interaction.");
}

 

We have used the isEnabled() methods from the WebElement to check if the element is enabled for the interaction or not. So if the element is enabled to interact it will show us the message printed out as “Element is enabled for interaction.”, otherwise “Element is disabled for interaction.”

69. How does one get the current page URL in Selenium?

To fetch the current page of the URL, we use the following code:

string currentUrl = driver.Url;
Console.WriteLine("Current URL: " + currentUrl);

 

We have a driver.Url() to get the URL of the current page and then store it in the variable type string currentUrl. Finally the Console.WriteLine helps us to print out the current URL. 

70. How can one retrieve the title of the webpage in Selenium?

We use the driver.getTitle() command, to fetch the page title in Selenium. The output of this code returns a string that contains the title of the webpage.

Selenium Tricky Interview Questions

71. How do we handle a scenario where an element's ID changes dynamically on each page load?

We can handle this scenario where an element's ID changes dynamically on each page load using:

  1. We can use a partial ID matching with XPath: //input[starts-with(@id, 'partial_id')]
  2. We can use other stable attributes like name, class, or data-* attributes
  3. We can use parent-child relationships in your locator strategy
  4. We can implement custom dynamic locators using JavaScript

72. How can we handle testing of an application that uses Web Components extensively?

We can handle testing of an application that uses Web Components extensively using:

  1. We can use Shadow DOM piercing techniques to interact with elements inside components
  2. We can test component lifecycle and property/attribute changes
  3. We can verify event handling and custom event dispatching
  4. We can consider using Web Component testing libraries alongside Selenium

73. What would we do if an element is loading too slowly in Selenium?

We can follow these steps if an element is loading too slowly in Selenium:

  1. Increase Implicit Wait: We can set a higher implicit wait time.
    driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
  2. Use Explicit Wait: We can prefer explicit waits for the specific element instead of relying on a global implicit wait.
  3. Check Network Conditions: We can ensure the test environment is not experiencing network delays.

74. How can we handle date pickers in Selenium WebDriver?

We can handle date pickers by:

  • Direct Input: If the date field allows typing, use sendKeys() to input the date.
dateElement.sendKeys("31/08/2024");
  • Custom Logic: If it’s a complex date picker, navigate through the picker by locating and clicking elements based on the required date.

75. How would you test an infinite scroll page using Selenium?

We can test an infinite scroll page by:

  1. Scrolling in increments and checking for new content
  2. Using JavaScript to scroll and wait for AJAX requests to complete
  3. Implementing a custom wait condition for new elements
  4. Setting a reasonable termination condition (e.g., number of scrolls or specific content)

76. How can we handle hidden elements in Selenium?

We can handle hidden elements in Selenium by:

  • Wait for Visibility: We can use WebDriverWait with ExpectedConditions.visibilityOfElementLocated.
  • Use JavaScriptExecutor: We can use JavaScriptExecutor to interact with the hidden element directly:
js.executeScript("arguments[0].click();", hiddenElement);
  • Modify DOM: We can alter the CSS to make the element visible.

77. How can we handle a dropdown that's not a standard SELECT element but a custom JavaScript implementation?

We can handle a dropdown that's not a standard SELECT element but a custom JavaScript implementation by:

  1. Locating and clicking the dropdown to open it
  2. Finding and clicking the desired option using its text or attributes
  3. Using Actions class for more complex interactions
  4. Waiting for any AJAX updates after the selection

78. How do we handle elements with the same attributes and no unique identifiers in Selenium?

We can handle such elements by using more complex XPath or CSS selectors that navigate the DOM structure:

// Example: Selecting the third element in a list
WebElement element = driver.findElement(By.xpath("(//tagname[@attribute='value'])[3]"));

79. How can we handle a scenario where the application uses shadow DOM extensively?

We can handle a scenario where the application uses shadow DOM extensively:

  1. We can use JavaScript to access shadow DOM elements
  2. We can utilize browser-specific commands (e.g., Chrome's /deep/ combinator)
  3. We can use custom locator strategies that can pierce shadow DOM
  4. We can consider using newer Selenium versions with better shadow DOM support

80. How can we check if a text is present on a web page using Selenium?

We can check if text is present by verifying the page source or using XPath:

boolean isTextPresent = driver.getPageSource().contains("Text to check");

 

Also, we can use it in this way:

boolean isTextPresent = driver.findElements(By.xpath("//*[contains(text(), 'Text to check')]")).size() > 0;

81. How can we test an application that uses WebSockets for real-time updates?

We can test an application that uses WebSockets for real-time updates:

  1. Using browser's developer tools to monitor WebSocket traffic
  2. Implementing custom wait conditions for WebSocket updates
  3. Mocking WebSocket server for controlled testing
  4. Using specialized WebSocket testing libraries alongside Selenium

82. How can we test file downloads in a headless browser environment?

We can test file downloads in a headless browser environment:

  1. By configuring browser preferences to specify download directory
  2. Using file system operations to verify downloaded files
  3. By intercepting network requests to verify download initiation
  4. For Chrome, use --headless=new mode which supports downloads

83. How can we handle CAPTCHA in Selenium?

CAPTCHA is designed to prevent automation, so it’s generally not recommended to automate it. However, if necessary for testing:

  • Disable CAPTCHA: Work with the development team to disable CAPTCHA in test environments.
  • Use a Third-Party Service: Integrate with services that solve CAPTCHA (like DeathByCaptcha, 2Captcha) for test environments.

84. How would we handle testing of an application that uses client-side encryption for form submissions?

We can handle testing of an application that uses client-side encryption for form submissions:

  1. By mocking the encryption function for predictable test data
  2. By implementing JavaScript execution to access encrypted data
  3. Using proxy tools to intercept and decrypt network traffic
  4. By testing the encryption function separately from the submission process

85. How can we test responsive design effectively using Selenium?

We can test responsive design effectively using Selenium:

  1. By using Selenium's window management to resize the browser
  2. By implementing tests for different viewport sizes
  3. By using CSS media query breakpoints to guide test scenarios
  4. By combining Selenium with mobile emulation capabilities

Must Read Ruby on Rails Interview Questions

Selenium MCQ Questions

In this section of the article “Top 50+ Selenium Interview Questions and Answers (2023)”, we will discuss some important MCQ questions on Selenium. Here are as follows:

1. What does selenium mean?

  1. Programming Language
  2. Web testing framework
  3. Extension
     

Answer: B

2. What is the purpose of TestNG?

  1. creating GUI interfaces for Selenium tests.
  2. managing the test data.
  3. parallelizing the test execution.
  4. generating the HTML reports.
     

Answer: C

3. Choose the programming languages that are commonly used with Selenium?

  1. Python, Java, C#
  2. Ruby, PHP, HTML
  3. JavaScript, C++, Swift
  4. Kotlin, Perl, Objective-C
     

Answer: A

4. Choose the command that can be used for navigating the specific URL?

  1. open()
  2. navigate()
  3. get()
  4. load()
     

Answer: C

5. How the screenshot can be taken in the Selenium web driver?

  1. using captureScreenshot() method
  2. using takeScreenshot() method
  3. using saveScreenshot() method
  4. using screenshot() method
     

Answer: B

6. How the events in the Selenium web driver can be handled?

  1. Using the acceptAlert() method
  2. Using the dismissAlert() method
  3. Using the sendKeys() method
  4. All of the above
     

Answer: D

7. How the Selenium web driver can refresh the current web page?

  1. refreshPage()
  2. reload()
  3. refresh()
  4. navigate().refresh()
     

Answer: D

8. How the "enter" key on a keyboard can be pressed by using the command in the selenium web driver?

  1. sendKeys(Keys.ENTER)
  2. pressEnter()
  3. enterKey()
  4. sendKeys(Enter)
     

Answer: A

9. How can we switch to the i-frame element in selenium web driver?

  1. switchFrame()
  2. selectFrame()
  3. switchToFrame()
  4. switchTo().frame()
     

Answer: D

10. What does the "executeScript" method use for?

  1. To execute a test case.
  2. To execute JavaScript code in the context of the current browser window.
  3. To generate test reports.
  4. To take a screenshot.
     

Answer: B

Check this out : Xpath in Selenium

Frequently Asked Questions

Q. What are the 4 major components of Selenium WebDriver?

The 4 major components of Selenium WebDriver are Selenium Client Library (provides programming interfaces), Web Driver Language Bindings (provides additional functionalities to client library), JSON Wire Protocol (provides a common interface to make communications easier), and Browser Drivers (executable files that help WebDriver to communicate with other web browsers.). 

Q. What are the 3 parts of Selenium?

Selenium has three parts: Selenium WebDriver, Selenium IDE, and Selenium Grid. Selenium IDE is used for automating web browsers and allows us to use a programming language to control browsers. Selenium IDE is used to record and playback for Selenium scripts, and no need to have programming knowledge. Selenium Grid is used to run Selenium tests on multiple browsers simultaneously.

Q. Why do we use WebDriver in Selenium?

Basically, WebDriver in Selenium provides the programmatic interface, which is used to automate the web browsers so that interaction with web elements and tests can be performed on the web applications.

Q. What is Selenium used for in QA testing?

Selenium is used for the automation of web browsers with QA testing, which basically helps in regression testing, functional testing, and load testing. It also helps in automating the repetitive tasks.

Q. What is POM Selenium?

POM stands for Page Object Model in the Selenium, which is a design pattern that promotes the structured approach for organizing and maintaining the automated tests by creating the classes.

Conclusion

This article contains all of the Selenium interview questions for freshers and Selenium interview questions and answers for experienced applicants. We hope you found solutions to this article’s most often asked Selenium Interview questions and WebDriver interview questions also. The answers to selenium interview questions presented here are also beneficial in comprehending Selenium fundamentals and advanced WebDriver subjects. 

Check out Top Linux Interview Questions, Selenium Interview Questions, Operating System Interview Questions and Typescript Interview Questions to ace your interviews. Also, check out our JUnit Introduction with Eclipse article if you want to learn more about unit testing. Do upvote our blog to help other ninjas grow.

Head over to our practice platform Code360 to practise top problems, attempt mock tests, read interview experiences, and much more.!

Happy Reading!

Live masterclass