Tutorials Hut

Top Selenium Interview Questions and Answers

This section helps with Selenium interview. Contains selenium basic and advance interview questions and answers.

Basic Level Selenium Interview Questions and Answers

    1. What is Selenium and Selenium WebDriver?

Selenium is a popular open-source testing framework used for automating web applications.

.Selenium WebDriver is a tool used for automating web applications on different browsers.

    1. What are the different components of Selenium?

Selenium consists of four components – Selenium IDE, Selenium RC, Selenium WebDriver, and Selenium Grid.

    1. What is Selenium IDE?

Selenium IDE is a Firefox plugin that is used for record and playback testing.

    1. What is Selenium Grid?

Selenium Grid is used for parallel testing of multiple browsers and operating systems.

    1. How do you identify web elements in Selenium?

Web elements can be identified using various locators such as ID, name, class name, tag name, link text, partial link text, and CSS selector.

    1. What is an XPath?

XPath is a language used for navigating XML documents, and is also used for locating elements in Selenium. There are two types of xpath:

    • Relative Xpath
    • Absolute Xpath
    1. What is a relative XPath?

Relative XPath starts with double forward slashes (//) and it locates an element based on its position relative to another element in the HTML DOM. It allows XPath to search for elements anywhere on the page, without having to know the exact location of the element in the document hierarchy.

//div[@class='menu']/ul/li[2]/a

The double forward slash (//) means that the search should start at any point in the HTML document and move downward

    1. What is a Absolute XPath?

Absolute XPath begins with a single forward slash (/) and starts searching from the root node of the HTML document. It specifies the complete path of an element from the root of the document to the target element. Here is an example of an absolute XPath expression:

    1. Difference between Relative and Absolute XPath:

The main difference between relative and absolute XPath is that the former starts with a double forward slash (//) and the latter starts with a single forward slash (/). Relative XPath is more flexible and can be used to locate elements anywhere on the page, while absolute XPath is more specific and requires the exact path to the element.

    1. What is a CSS selector?

A CSS selector is a pattern used to select web elements based on their CSS attributes.

WebElement element = driver.findElement(By.cssSelector("element_cssselector"));
    1. What is the difference between getText() and getAttribute() in Selenium?

getText() is used to retrieve the visible text of a web element, while getAttribute() is used to retrieve the value of an attribute of a web element.

    1. What is a WebDriver wait?

A WebDriver wait is used to pause the execution of a test until a certain condition is met.

Implicit and explicit wait are two types of waits used to achieve it.

implicit wait: An implicit wait is a global wait that waits for a specified amount of time for an element to become available before throwing an exception.

explicit wait: An explicit wait is a wait that waits for a specific condition to become true before moving on to the next step in the test.

    1. What is Page Object Model (POM) in Selenium?

Page Object Model is a design pattern that is used to create an object repository for web elements on a page. It means that each web page is represented as a separate Java class, and each web element is represented as a method in that class. This approach makes the test scripts more modular, reusable, and easy to maintain.

    1. What programming languages does Selenium support?

Selenium supports multiple programming languages such as Java, Python, C#, Ruby, etc.

    1. What is TestNG in Selenium?

TestNG is a testing framework for Java that is used to write and execute automated test cases. TestNG provides various features, such as parallel execution, data-driven testing, reporting, and grouping of test cases. TestNG is used in Selenium to write and execute test cases in a structured and organized manner.

    1. What are the advantages of using TestNG in Selenium?

TestNG is a testing framework that provides various features such as annotations, grouping, parallel execution, reporting, and data parameterization. Some of the advantages of using TestNG in Selenium are:

    • Easy to create and manage test cases.
    • Supports parallel execution of tests.
    • Provides flexible configuration options.
    • Provides better reporting and logging.
    • Supports data parameterization and grouping of test cases.
    1. What is a test case, test suite and test runner in Selenium?

A test case is a set of instructions that are executed to verify a specific functionality of a web application.

A test suite is a collection of test cases that are executed together. A test runner is a tool that is used to execute test cases.

    1. What is the difference between driver.close() and driver.quit() in Selenium?

driver.close() closes the current browser window, while driver.quit() closes all the windows opened by the WebDriver instance.

    1. What is a headless browser?

A headless browser is a browser that can be run without a graphical user interface, and is used for automated testing. Example of headless browsers:PhantomJs, Headless Chome etc.

    1. How do you handle cookies in Selenium?

Cookies are used to store user information, preferences, and login details. They can be handled in Selenium using the “Cookies” interface. The “getCookies()” method is used to get all the cookies for the current domain. The “addCookie()” method is used to add a new cookie to the browser. The “deleteCookie()” method is used to delete a specific cookie from the browser.

    1. What is Page Object Model (POM) in Selenium?

Page Object Model is a design pattern that is used to create an object repository for web elements on a page. It means that each web page is represented as a separate Java class, and each web element is represented as a method in that class. This approach makes the test scripts more modular, reusable, and easy to maintain.

Advanced Level Selenium Interview Questions and Answers

    1. How do you handle dynamic web elements in Selenium?

Dynamic web elements are those that change their properties such as ID, name, class, etc. every time the page is loaded. To handle dynamic web elements in Selenium, we can use various locators such as Xpath, CSS Selector, and Regular Expression.

For example, we can use a partial ID or class name of the dynamic element and combine it with a wildcard character (*) to identify the element.

    1. How to identify web elements in Selenium with examples?

There are various techniques available to locate web elements, and each technique has its advantages and disadvantages.

Locating elements by ID:

ID is a unique identifier that is assigned to an element. The ID attribute is generally used to identify elements that are expected to remain unchanged on the page. Example of how to locate an element using its ID:

WebElement element = driver.findElement(By.id("element_id"));

Locating elements by Name:

The name attribute is used to identify elements that have a specific name assigned to them. Example of how to locate an element using its name:

WebElement element = driver.findElement(By.name("element_name"));

Locating elements by Class Name:

The class name attribute is used to identify elements that belong to a specific CSS class. Example of how to locate an element using its class name:

WebElement element = driver.findElement(By.className("element_classname"));

Locating elements by Tag Name:

The tag name is the name of the HTML tag that is used to define an element. Example of how to locate an element using its tag name:

WebElement element = driver.findElement(By.tagName("element_tagname"));

Locating elements by Link Text:

The link text is the text that is displayed on a link. Example of how to locate an element using its link text:

WebElement element = driver.findElement(By.linkText("element_linktext"));

Locating elements by Partial Link Text:

The partial link text is a part of the text that is displayed on a link. Example of how to locate an element using its partial link text:

WebElement element = driver.findElement(By.partialLinkText("element_partiallinktext"));

Locating elements by CSS Selector:

CSS selectors are used to select elements based on their attributes. Example of how to locate an element using its CSS selector:

WebElement element = driver.findElement(By.cssSelector("element_cssselector"));

Locating elements by Xpath:

Xpath is a language used to select elements in an XML document. Example of how to locate an element using its Xpath:

WebElement element = driver.findElement(By.xpath("element_xpath"));
    1. How do you handle synchronization issues in Selenium?

Synchronization issues occur when the script execution moves faster than the page load time or element rendering time. This can cause the script to fail if it attempts to interact with an element that is not yet visible or available on the page.

To handle synchronization issues in Selenium, we can use various types of waits such as implicit, explicit, and fluent waits. These waits allow the script to pause for a certain amount of time until a specific condition is met, such as the presence or visibility of an element.

We can also use the Thread.sleep() method to pause the execution for a certain amount of time, but this is not recommended as it is a static wait and can cause the script to wait longer than necessary.

    1. How do you handle file uploads in Selenium?

To handle file uploads in Selenium, we can use the sendKeys() method to simulate the user clicking the ‘Choose File’ button and then entering the file path in the file upload dialog box. For example:

WebElement uploadFile = driver.findElement(By.id(“uploadFile”));

uploadFile.sendKeys(“C:\test\file.txt”);

We can also use third-party libraries such as AutoIT or Robot Class to handle file uploads.

    1. How do you handle multiple windows in Selenium?

To handle multiple windows in Selenium, we can use the getWindowHandles() method to get the window handles of all the open windows, and then switch between them using the switchTo() method.

For example, to switch to the second window:

Set<String> handles = driver.getWindowHandles();
Iterator<String> it = handles.iterator();

String parentWindow = it.next();

String childWindow = it.next();

driver.switchTo().window(childWindow);
    1. How do you handle browser navigation in Selenium?

To handle browser navigation in Selenium, we can use various methods such as navigate().to(), navigate().back(), navigate().forward(), and navigate().refresh().

For example, to navigate to a URL:

driver.navigate().to("http://www.google.com");
    1. How do you handle multiple windows in Selenium?

To handle multiple windows in Selenium, we can use the getWindowHandles() method to get the window handles of all the open windows, and then switch between them using the switchTo() method.

For example, to switch to the second window:

Set<String> handles = driver.getWindowHandles();
Iterator<String> it = handles.iterator();
String parentWindow = it.next();
String childWindow = it.next();
driver.switchTo().window(childWindow);
    1. How do you handle browser navigation in Selenium?

To handle browser navigation in Selenium, we can use various methods such as navigate().to(), navigate().back(), navigate().forward(), and navigate().refresh().

For example, to navigate to a URL:

driver.navigate().to("http://www.google.com");
    1. How do you handle frames and iframes in Selenium?

To handle frames and iframes in Selenium, we can use the switchTo() method to switch the focus of the driver to the frame or iframe. For example, to switch to a frame by index:

driver.switchTo().frame(0);

To switch back to the default content:

driver.switchTo().defaultContent();
    1. What are the different types of locators in Selenium?

Selenium supports various types of locators such as ID, name, class name, tag name, link text, partial link text, CSS Selector, and XPath. These locators are used to identify web elements on a web page.

    1. What is the difference between findElement() and findElements() methods in Selenium?

findElement() and findElements() are methods used to locate web elements on a web page using Selenium.

Difference between findElement() and findElements():

Return Type: findElement() returns a single web element that matches the specified criteria, while findElements() returns a list of web elements that match the specified criteria.

Exception Handling: If findElement() does not find any matching elements, it throws a NoSuchElementException. On the other hand, findElements() returns an empty list if no matching elements are found, so no exception is thrown.

Use: findElement() is used when you want to locate a single element on the page, such as a button or a text field. findElements() is used when you want to locate multiple elements, such as a list of checkboxes or a table.

// Find a single element using findElement()

WebElement element = driver.findElement(By.id("username"));

// Find multiple elements using findElements()

List<WebElement> elements = driver.findElements(By.tagName("a"));

In the first example, findElement() is used to locate a single element with an ID of “username”. In the second example, findElements() is used to locate all the anchor tags on the page and return a list of web elements.

    1. How do you handle SSL certificate errors in Selenium?

SSL certificates are used to establish a secure connection between the browser and the server. They can be handled in Selenium using the “Capability” class. The “setAcceptInsecureCerts()” method is used to accept insecure SSL certificates.

SSL certificate errors occur when the website uses a self-signed or invalid SSL certificate. To handle SSL certificate errors in Selenium, we can create a custom DesiredCapabilities object and set the “acceptSslCerts” capability to true.

    1. How to handle SSL certificate errors in Selenium in different browsers?

SSL (Secure Sockets Layer) certificate errors occur when there is an issue with the certificate validation process. This can cause issues when running automated tests in Selenium, as some browsers may block the connection to a website that has an invalid SSL certificate. Here are the steps to handle SSL certificate errors in different browsers:

Chrome:

ChromeOptions class and set the –ignore-certificate-errors flag is used to handle SSL certificate errors in Chrome.

ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-certificate-errors");
WebDriver driver = new ChromeDriver(options);

Firefox:

acceptInsecureCerts capability to true to ignore SSL certificate errors.is used to handle SSL certificate errors in Firefox.

FirefoxOptions options = new FirefoxOptions();
options.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
WebDriver driver = new FirefoxDriver(options);

Edge:

EdgeOptions class and set the setAcceptInsecureCerts method to true is used to handle SSL certificate errors in Edge.

EdgeOptions options = new EdgeOptions();
options.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
WebDriver driver = new EdgeDriver(options);

Safari:

Set the trustSSLCertificates capability to true is used to handle SSL certificate errors in Safari.

SafariOptions options = new SafariOptions();
options.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
WebDriver driver = new SafariDriver(options);
    1. How do you handle popup windows in Selenium?

Popup windows are small windows that appear on top of the main browser window. To handle popup windows in Selenium, we can use the getWindowHandles() method to get the window handles of all the open windows, and then switch to the popup window using the switchTo() method.

For example:

Set<String> handles = driver.getWindowHandles();
Iterator<String> it = handles.iterator();
String parentWindow = it.next();
String childWindow = it.next();
driver.switchTo().window(childWindow);

    1. How do you handle AJAX calls in Selenium?

AJAX calls are asynchronous requests that are made to the server without refreshing the entire page. To handle AJAX calls in Selenium, we can use the WebDriverWait class to wait for a certain condition to be met, such as the presence of a particular element or the completion of an AJAX call.

For example:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("elementId")));
    1. How do you handle drag and drop actions in Selenium?

To handle drag and drop actions in Selenium, we can use the Actions class to perform the drag and drop operation. For example, to drag an element to a new location:

WebElement element = driver.findElement(By.id("elementId"));
Actions actions = new Actions(driver);
actions.dragAndDropBy(element, 100, 100).build().perform();
    1. How do you handle dynamic wait times in Selenium?

Dynamic wait times occur when the time required for an element to load or become visible varies each time the page is loaded. To handle dynamic wait times in Selenium, we can use the FluentWait class to set a maximum wait time and polling interval for the element.

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("elementId"));
}
});
    1. How do you handle mouse hover actions in Selenium?

To handle mouse hover actions in Selenium, we can use the Actions class to move the mouse to the desired element and then perform the desired action, such as clicking or selecting an option.

WebElement element = driver.findElement(By.id("elementId"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
    1. What is the difference between Implicit and Explicit waits in Selenium?

Implicit wait is a type of wait that is set globally for the WebDriver instance. It means that the WebDriver will wait for a certain amount of time before throwing an exception if an element is not found on the page. Implicit wait is set using the “implicitlyWait()” method.

Explicit wait is a type of wait that is set locally for a specific element or condition. It means that the WebDriver will wait for a certain amount of time until a specific condition is met. Explicit wait is set using the “WebDriverWait” class.

    1. How do you perform keyboard actions in Selenium?

Keyboard actions can be performed in Selenium using the “Actions” class. The “sendKeys()” method is used to send text or keys to the keyboard. The “keyDown()” method is used to simulate a key press, and the “keyUp()” method is used to simulate a key release.

    1. What is dataprovider in testNG with example?

In TestNG, DataProvider is a feature that allows you to run a test method with multiple sets of data. It helps to create data-driven tests where you can test the same functionality with different input values.This helps to create more robust and comprehensive tests that cover different scenarios and edge cases.

Example of how to use DataProvider in TestNG:

@Test(dataProvider = "testData")
public void testLogin(String username, String password) {
    // Perform login operation with the given username and password
}
@DataProvider(name = "testData")
public Object[][] testData() {
    return new Object[][] {
        { "user1", "password1" },
        { "user2", "password2" },
        { "user3", "password3" }
    };
}

In the above example, we have a test method called testLogin that takes two parameters – username and password. We have also defined a DataProvider method called testData that returns a two-dimensional array of objects. Each row of the array represents a set of data that will be passed to the test method. In this case, we have three sets of data – user1/password1, user2/password2, and user3/password3.

When you run the test, TestNG will invoke the testLogin method three times with each set of data. This will test the login functionality with three different combinations of username and password.

It’s important to note that the data returned by the DataProvider method must match the parameters of the test method. TestData method returns a two-dimensional array of objects, which matches the two parameters of the testLogin method.

    1. How to achieve parallel testing using testNG?

TestNG provides a built-in feature to perform parallel testing, which allows you to run multiple test methods in parallel to save time and improve efficiency. Here are the steps to achieve parallel testing using TestNG:

Add the parallel attribute to the test tag in your testng.xml file. This attribute specifies the type of parallel testing you want to perform. For example, you can specify:

<suite name=”My Test Suite” parallel=”tests”>

This will run all test methods in parallel.

Add the thread-count attribute to specify the number of threads to use for parallel testing.

<suite name=”My Test Suite” parallel=”tests” thread-count=”3″>

This will run all test methods in parallel using three threads.

Add the @Test annotation to your test methods and set the threadPoolSize and invocationCount attributes. These attributes specify the number of threads to use for each test method and the number of times to run each test method, respectively.

@Test(threadPoolSize = 3, invocationCount = 3)

public void myTest() {

    // Test code goes here

}

This will run the myTest method three times, each time in parallel using three threads.

By default, TestNG uses a separate instance of the test class for each thread. If you need to share data between threads, you can use the @BeforeTest and @AfterTest annotations to set up and tear down any shared resources.