Selenium Interview Questions for Experienced

Anshul
15 min readAug 9, 2023

--

1. State the major difference between “assert” and “verify” commands in Selenium.

Both “assert” and “verify” commands check whether the given condition is true or false and the only difference between them is that:

  • Assert: Assert condition stops the execution of the testing if the given condition is false else would continue with the further tests.
  • Verify: Verify the condition doesn’t stop the flow of execution irrespective of the condition being true or false.

2. Explain the same-origin policy and how Selenium handles it?

The same Origin policy is a feature adopted for security purposes that allows a web browser to run scripts from one webpage to access the contents of another webpage provided both pages have the same origin. The URL scheme, hostname, and port number combo are referred to as the origin. This policy was introduced to prevent access to sensitive data on one webpage by another for ill purposes. Consider a Java program used by scaler.com, the program can access domain pages like scaler.com/mentors, scaler.com/courses but none from different domains like facebook.com.

The Selenium Server (Selenium RC) acts as a client-configured HTTP proxy and “tricks” the browser into believing that Selenium Core and the web application being tested come from the same origin.

3. Explain the pause feature in Selenium IDE.

The pause feature is built to handle exceptions in the test script by allowing the user to pause at the statement causing the exception and enter the debug mode by clicking on the pause icon on the top right corner of the IDE. This feature prevents the entire test case’s failure and gives the user a chance to correct the error instantly.

4. With the help of code snippets, explain how we can create right-click and mouse hover actions in Selenium.

The following code can replicate right-click action:

actions action = newActions(driver);
WebElement element = driver.findElement(By.id("elementId"));
action.contextClick(element).perform();

The following code can replicate the mouse hover action:

actions action = newActions(driver);
WebElement element = driver.findElement(By.id("elementId"));
action.moveToElement(element).perform();

Unlock the Power of Automation with Our Comprehensive Selenium Full Training — Accelerate Your Testing Success Today!

Selenium WebDriver with Java and Python (Basics + Advance + Architect)

Selenium WebDriver with Java and Python (Basics + Advance + Architect)
Selenium WebDriver with Java and Python (Basics + Advance + Architect)

5. Can we handle a windows-based pop-up in Selenium, and if not, then what are the alternatives?

No, Selenium doesn’t support windows-based pop-ups as it’s an automated testing tool built for web application-based testing. However, with the support of third-party tools like AutoIT, Robot class, etc., windows-based pop-ups can be handled in selenium.

6. Can you capture a screenshot using Selenium? If yes, write a simple code to illustrate the same.

Yes, using a web driver in Selenium, we can capture the screenshot. Following is the code to do the same:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TakeScreenshot {
WebDriver drv;
@ Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
drv.get("https://google.com");
}
@ After
public void tearDown() throws Exception {
drv.quit();
}
@ Test
public void test() throws IOException {
// Capture the screenshot
File scrFile = ((TakeScreenshot)drv).getScreenshotAs(OutputType.FILE);
// Code for pasting screenshot to a user-specified location
FileUtils.copyFile(scrFile, new File("C:\\Screenshot\\Scr.jpg"))
}
}

7. Explain different types of framework and connection of Selenium with Robot Framework.

The following are the different types of frameworks:

  • Behavior-Driven Development Framework: This type of framework provides a readable and easily understandable format to Business Analysts, Developers, Testers, etc.
  • Data-Driven Testing Framework: This type of framework helps separate test data from the test-script logic by storing test data in some external database in the form of key-value pairs. These keys can be used for accessing as well as populating data into the test scripts.
  • Keyword-Driven Testing Framework: This type of framework is an extension of the data-driven testing framework. In addition to separating test data and the test-script logic, it also separates a part of the test script code by storing it in an external data file.
  • Library Architecture Testing Framework: This type of framework groups common steps into functions under a library and calls these functions as and when required.
  • Module-Based Testing Framework: This type of framework divides each test application into several isolated and logical modules, with each module having its distinct test script.
  • Hybrid Testing Framework: This type of framework is a combination of the above-mentioned frameworks leveraging all their good features.

Robot Framework is a modular open-source automation framework that can interact with 3rd party libraries and functions. To execute a web testing library such as Selenium, a test automation runner or an automation wrapper is required, which is provided to it in the form of Robot Framework. Other popular test runners to serve the same purpose are MSTest, TestNG, Nunit, Junit, etc.

The below diagram shows the connection of the Robot framework to the Selenium library:

8. Demonstrate usage of Selenium through a test application.

You need the following prerequisites to run a demo Selenium test script:

  • Java SDK in your respective Operating System.
  • A Java-based IDE such as Eclipse or IntelliJ.
  • A Selenium WebDriver is to be added as a dependency to Java IDE.
package scalerAcademy;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
public class MyFirstTestClass {
public static void main(String[] args) throws InterruptedException {
//It sets the system property to the given value.
System.setProperty("webdriver.gecko.driver","D:\\Softwares\\geckodriver.exe”);
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com/");
//Launch website in the browser
driver.manage().window().maximize();
//The sleep pauses the execution of the thread for 5000 ms.
Thread.sleep(5000);
driver.quit();
}
}

Once you run the above script in a Java IDE, you’ll get the following execution logs displayed in your IDE window.

9. Explain basic steps of Selenium testing and its widely used commands via a practical application.

Selenium testing can be divided into the following seven basic elements:

1. Creating an instance of a Webdriver: This is the first step for all the usages of a Selenium webdriver API. An instance of a webdriver interface is created using a constructor of a particular browser. This webdriver instance is used to invoke methods and access other interfaces. The following are the most commonly used commands for initializing a web driver:

Firefox:
WebDriver driver = new FirefoxDriver();
Chrome:
WebDriver driver = new ChromeDriver();
Safari Driver:
WebDriver driver = new SafariDriver();
Internet Explorer:
WebDriver driver = new InternetExplorerDriver();

2. Navigating to a webpage: The second step after initializing an instance of a webdriver, is to navigate to a particular webpage you want to test. The following are the most commonly used commands for webpage navigation:

Navigate to URL: 
driver.get(“https://www.example.com”)
driver.navigateo.to(“https://www.example.com”)
Refresh page:
driver.navigate().refresh()
Navigate forward in browser history:
driver.navigate().forward()
Navigate backward in browser history:
driver.navigate().backward()

3. Locating an HTML element on the webpage: To interact with a web element and perform actions on it like clicking a button or entering text, we first need to locate the desired elements such as the button or the textbox on the web page. The following are the most commonly used commands for web element navigation:

Locating by ID:
driver.findElement(By.id("q")).sendKeys("Selenium 3");
Location by Name:
driver.findElement(By.name("q")).sendKeys ("Selenium 3");
Location by Xpath:
driver.findElement(By.xpath("//input[@id==’q’])).sendKeys("Selenium 3");
Locating Hyperlinks by Link Text:
driver.FindElement(By.LinkText("edit this page")).Click();
Locating by ClassName
driver.findElement(By.className("profileheader"));
Locating by TagName
driver.findElement(By.tagName("select')).click();
Locating by LinkText
driver.findElement(By.linkText("NextPage")).click();
Locating by PartialLinkText
driverlindElement(By.partialLinkText(" NextP")).click();

4. Performing actions on an HTML element: Once we have located the HTML element, the next step is interacting with it. The following are the most commonly used commands for performing actions on an HTML elements:

Entering a username
usernameElement.sendKeys("example");
Entering a password
passwordElement.sendKeys("Raw");
Submitting a text input element
passwordElement.submit();
Submitting a form element:
formElement.submit();

5. Anticipating browser response from the action: Once an action is performed, anticipating a response from the browser to test comes under this step. It takes a second or two for the action to reach the browser, and hence wait is often required for this step. There are two main types of wait conditions:

Implicit Wait: It sets a fixed, definite time for all the webdriver interactions. It’s slightly unreliable as web driver response times are usually unpredictable. Eg:

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

Explicit Wait: This type of wait condition sets an expected condition to occur on the web page or a maximum wait time for all the webdriver interactions. Eg:

WebElement messageElement = wait.until(      ExpectedConditions.presenceOfElementLocated(By.id("loginResponse")) );

6. Running tests and recording their results using a test framework: in this step, we run tests in an automated test script to evaluate an application’s function and performance. Various test frameworks are used for this step, such as:

  1. JUnit for Java
  2. NUnit for C#
  3. Unittest or Pyunit for Python
  4. RUnit for Ruby

Most frameworks use some sort of asset statement to verify their test results from the expected results. Eg:

assertEquals (expectedMessage, actualMessage);

7. Concluding a test: In this step, we conclude a test by invoking a quit method on the driver variable. This step closes all the webpages, quits the WebDriver server, and releases the driver. Eg:

driver.quit();

The following is an example of an app that covers all the steps mentioned above:

import org.openqa.selenium.By,
import org.openqa.selenium.WebElement,
import org.openqa.selenium.support.ni.ExpectedConditiof, import org.openqa.selenium.support.ni.WebOriverWait,
import org.junit.Assert;
public class Example {
public static void main(String[] args) {
// Creating a driver instance
WebDriver driver = new FirefoxDriver(),
// Navigate to a web page
­driver.get("http://www.foo.com");
// Enter text to submit the form
WebElement usernameElement = driver.findElement( By.name("username"));
WebElement passwordElement = driver.findElement(By.name(”password"));
WebElement formElement = driver.findElement(By.id(”loginForm"));
usernameElement.sendKeys("Scaler Academy");
passwordElement.sendKeys("Raw");
formElement.submit(); // submit by form element
//Putting an explicit wait
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement messageElement = wait.until(
ExpectedConditions.presenceofElementLocated(By.id(”loginResponse"))
) ;
// Run a test
String message = messageElement.getrept();
String successMsg = "Welcome to foo. You logged in successfully.”;
Assert.assertEquals (message, successMsg);
// Conclude a test
driver.quit();
}
}

10. What do you understand about the Page Object Model in the context of Selenium? What are its advantages?

Page Object Model (POM) is a design pattern that generates an Object Repository for web UI elements and is widely used in test automation. The paradigm has the advantage of reducing code duplication and improving test maintenance. According to this paradigm, each web page in the application should have its own Page Class. This Page class will identify the web page’s WebElements and also has Page methods that operate on those WebElements. The names of these methods should correspond to the tasks they perform, for example, if a loader is waiting for the payment gateway to appear, the POM method name could be waitForPaymentScreenDisplay().

The following are the advantages of the Page Object Model (POM) :

  • According to the Page Object Design Pattern, user interface activities and flows should be separated from verification. Our code is clearer and easier to understand as a result of this notion.
  • The second advantage is that the object repository is independent of test cases, allowing us to reuse the same object repository with different tools. For example, we can use Selenium to combine Page Object Model with TestNG/JUnit for functional testing and JBehave/Cucumber for acceptability testing.
  • Because of the reusable page methods in the POM classes, code gets less and more efficient.
  • Methods are given more realistic names that can be easily associated with the UI operation. If we land on the home page after clicking the button, the function name will be ‘gotoHomePage()’.

11. What is Jenkins and what are the benefits of using it with Selenium?

Hudson Lab’s Jenkins is the most popular open-source continuous integration technology. It’s cross-platform, meaning it can run on Windows, Linux, Mac OS, and Solaris. Jenkins is a Java application. Jenkin’s main purpose is to keep track of any job, such as SVN (Apache Subversion) checkouts, cron jobs, or application states. When a specific event in an application occurs, it triggers pre-configured actions.

The following are the features of Jenkins:

  • Jenkins generates a list of all changes made in SVN repositories, for example.
  • Jenkins gives permanent links to the most recent build or failed build, which can be utilized for convenient communication.
  • Jenkins is simple to install using either a direct installation file (exe) or a war file for deployment via the application server.
  • Jenkins can be set up to send the content of the build status to an email address.
  • Simple Configuration: Jenkins makes it simple to set up multiple tasks.
  • Jenkins can be configured to run the automated test build on TestNg following every SVN build.
  • Jenkins documents the details of the jar, its version, and the mapping of build and jar numbers.
  • Plugins: Jenkins can be set to utilize features and additional functionality provided by third-party plugins.

Following are the reasons we use Jenkins with Selenium:

  • When you run Selenium tests in Jenkins, you can run them every time your program changes, and when the tests pass, you may deploy the software to a new environment.
  • Jenkins may execute your tests at a predetermined time.
  • The execution history as well as the Test Reports can be saved.
  • Jenkins allows you to develop and test a project in continuous integration using Maven.

12. How will you select a date from a datepicker in a webpage using Selenium for automated testing? Explain with a proper code.

In such types of questions, the interviewer wants to assess how clear your understanding is of the framework. It is a good practice to explain the code while you write it so that the interviewer is engaged at all points and does not feel left out. We will be considering an example on MakeMyTrip.

Here, we will be using the chrome browser and so we will be implementing the code for the chrome browser only. You can implement similar code for firefox and other browsers as well.

First of all, we create a package named browserSelection which contains a class defined for handling different types of browsers such as chrome, firefox that we may want to use.

package browserSelection;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SelectBrowser
{
static WebDriver driver;
public static WebDriver useChrome()
{
System.setProperty("webdriver.chrome.driver", "E:\\SeleniumLibs\\\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
return driver;
}
}

Next, we create a package named datepicker which will contain a class containing methods defined for selecting a specific date on the website of MakeMyTrip. We need to import this package into our driver class and call the respective methods.

package datepicker;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import browserSelection.SelectBrowser;
public class DatePick
{
WebDriver driver;
@BeforeMethod
public void startBrowser()
{
driver = SelectBrowser.useChrome();
}
@Test
public void selectDateUtil() throws InterruptedException, AWTException
{
//Modify Wait time as per the Network Ability in the Thread Sleep method
driver.get("https://www.makemytrip.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Thread.sleep(5000);
try
{
driver.findElement(By.xpath("//input[@id='hp-widget__depart']")).click();
Thread.sleep(2000);
Date sampleDate = new Date(); // initialising the date object with the current date
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM yyyy");
String date = formatter.format(sampleDate); // formatting the date object in dd-MMM yyyy format
String splitter[] = date.split("-");
String monthYear = splitter[1]; // storing the month and year concatenated string excluding the day number
String day = splitter[0]; // storing the day number in the current date
System.out.println(monthYear);
System.out.println(day);
        selectDate(monthYear,day); // function invocation
Thread.sleep(3000);
public void selectDate(String monthYear, String select_day) throws InterruptedException
{
List<WebElement> elements = driver.findElements(By.xpath("//div[@class='ui-datepicker-title']/span[1]"));
for (int i=0; i<elements.size();i++)
{
System.out.println(elements.get(i).getText());
//Selecting the month
if(elements.get(i).getText().equals(monthYear))
{
//Selecting the date
List<WebElement> days = driver.findElements(By.xpath("//div[@class='ui-datepicker-inline ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-datepicker-multi ui-datepicker-multi-2']/div[2]/table/tbody/tr/td/a"));
for (WebElement d:days)
{
System.out.println(d.getText());
if(d.getText().equals(select_day))
{
d.click();
Thread.sleep(10000);
return;
}
}
}
}
// if we do not find the matching month and year, we click on the arrow button to load new months.
driver.findElement(By.xpath("//div[@class='ui-datepicker-inline ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-datepicker-multi ui-datepicker-multi-2']/div[2]/div/a/span")).click();
selectDate(monthYear,select_day); // function invocation
}
@AfterMethod
public void endBrowser()
{
driver.quit();
}
}
}
}

In the above code, the function startBrowser() is used to invoke the useChrome() method from the imported package browserSelection. The function selectDateUtil() is used to select the current date from the date picker of the sample web page. The endBrowser() function is used to close the driver connections by invoking the quit() method.

13. What do you understand about broken links? How can you detect broken links in Selenium? Explain properly with code.

Links or URLs that are not reachable are known as broken links. They may be unavailable or inoperable due to a server issue. A URL’s status will always be 2xx, indicating that it is legitimate. There are a variety of HTTP status codes, each with its own set of functions. HTTP status 4xx and 5xx indicate an invalid request. The 4xx class of status codes is used for client-side errors, while the 5xx class is used for server response errors.

You should always check for broken links on your site to ensure that the user does not end up on an error page. If the rules aren’t updated appropriately, or the requested resources aren’t available on the server, the error will occur. Manual link checking is a time-consuming task because each web page may have a huge number of links, and the process must be performed for each page.

To find broken links in Selenium, follow the instructions below.

  • Using the <a> (anchor) tag, collect all of the links on a web page.
  • For each link, send an HTTP request.
  • Make that the HTTP response code is correct.
  • Based on the HTTP response code, determine whether the link is genuine or not.
  • Repeat the procedure for all of the links that were captured in the first step.
package SeleniumPackage;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class BrokenLinks {

public static void main(String[] args) {

String pageURL = "http://www.example.com";
String url = "";
HttpURLConnection huc = null;
int responseCode = 200;
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user\\Downloads\\selenium\\chromedriver_win32\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--window-size=1920,1200","--ignore-certificate-errors", "--silent");
WebDriver driver = new ChromeDriver(options);//Creating an instance of the WebDriver class

driver.manage().window().maximize();

driver.get(pageURL);

List<WebElement> links = driver.findElements(By.tagName("a")); // getting hold of all the elements having the anchor tag

Iterator<WebElement> it = links.iterator();
// Iterating over the obtained list of elements and checking them one by one
while(it.hasNext()){

url = it.next().getAttribute("href");

System.out.println(url);

if(url == null || url.isEmpty()){
System.out.println("The linked element has invalid href url.");
continue;
}

if(!url.startsWith(pageURL)){
System.out.println("URL belongs to another domain, skipping it.");
continue;
}

try {
huc = (HttpURLConnection)(new URL(url).openConnection());

huc.setRequestMethod("HEAD");

huc.connect(); // connecting to the url

responseCode = huc.getResponseCode(); // reading the response code on firing the url

if(responseCode >= 400){
System.out.println(url+" is a broken link");
}
else{
System.out.println(url+" is a valid link");
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

driver.quit();
}
}

Explanation — In the above code, we first set up the system properties and then initialize a webdriver object. We find all the elements in the web page having the anchor tag with the help of the findElements() method. Then, we iterate over the list obtained one by one and fire up the URL and read the response code received to check if it is a broken link or not.

14. What do you understand about window handle in the context of automated testing? How can you handle multiple windows in Selenium?

The window handle is a one-of-a-kind identifier that contains the addresses of all of the windows. Consider it a window pointer that returns the string value. Each browser will presumably have its own window handle. This window handle function aids in the retrieval of all window handles.
Syntax:

  • get.windowhandle(): This function is used to retrieve the current window's handle.
  • get.windowhandles(): This function is useful for retrieving the handles of all the windows that have been opened.
  • set: This method allows you to set the window handles as a string.
    set<string> set= driver.get.windowhandles()
  • switch to: This method aids in the switching of windows.
  • action: This method aids in the execution of specific window actions.

Let us consider an example code to understand better. We will open the website of example and then click on all the links available on the web page. Then, we will switch from the parent window to multiple different child windows and then switch back to the parent window at last.

package SeleniumPackage;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class WindowHandle_Demo {
public static void main(String[] args) throws Exception {
     System.setProperty("webdriver.chrome.driver", "C:\\Users\\user\\Downloads\\selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
// Loading the website
driver.get("http://www.example.com/");
String parent=driver.getWindowHandle(); // storing the parent window name as a string
List<WebElement> links = driver.findElements(By.tagName("a")); // storing the list of all the elements having an anchor tag
Iterator<WebElement> it = links.iterator();
// Iterating over the list elements one by one and clicking all the links to open new child windows
while(it.hasNext()){
it.next().click();
}
Set<String> s = driver.getWindowHandles(); // Storing the list of all the child windows
Iterator<String> I1= s.iterator();
// Iterating over the list of child windows
while(I1.hasNext())
{
String child_window=I1.next();
if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);
System.out.println(driver.switchTo().window(child_window).getTitle());
driver.close();
}
}
//switch to the parent window
driver.switchTo().window(parent);
}
}

In the above code, we open the landing page of example and then find all the elements having the anchor tag and click them to open multiple child windows. Then, we iterate over each of the child windows and print them as a string. Finally, having traversed over the entire list, we break from the loop and switch back to the parent window.

Unlock the Power of Automation with Our Comprehensive Selenium Full Training — Accelerate Your Testing Success Today!

Selenium WebDriver with Java and Python (Basics + Advance + Architect)

Selenium WebDriver with Java and Python (Basics + Advance + Architect)
Selenium WebDriver with Java and Python (Basics + Advance + Architect)

--

--

Anshul

DevRel 🥑 DevOps / Cloud Engineer | Terraform, Ansible, Docker & Kubernetes Enthusiast 🐳 GCP | Jenkins | Terraform Certified