Selenium Interview Questions and Answers

Selenium Interview Questions and Answers

Last updated on 05th Oct 2020, Blog, Interview Question

About author

Kernel (Sr Technical Project Manager )

Highly Expertise in Respective Industry Domain with 10+ Years of Experience Also, He is a Technical Blog Writer for Past 4 Years to Renders A Kind Of Informative Knowledge for JOB Seeker

(5.0) | 14521 Ratings 1258

Selenium is a free and open-source test automation suite used for automating web-based applications. It supports automation across different browsers, platforms, and programming languages

Using Selenium, we can automate the functional tests and easily integrate them with Maven, Jenkins, and other build automation and continuous integration tools.

Below we have listed the top 100 selenium interview questions & answers for fresher and  experienced candidates to clear the job interview. 

1. What is Automation Testing?

Ans:

Automation testing or Test Automation is a process of automating the manual process to test the application/system under test. Automation testing involves the use of a separate testing tool which lets you create test scripts which can be executed repeatedly and doesn’t require any manual intervention.

2. What are the benefits of Automation Testing?

Ans:

Benefits of Automation testing are:

  1. 1. Supports execution of repeated test cases
  2. 2. Aids in testing a large test matrix
  3. 3. Enables parallel execution
  4. 4. Encourages unattended execution
  5. 5. Improves accuracy thereby reducing human-generated errors
  6. 6. Saves time and money

3. Why should Selenium be selected as a test tool?

Ans:

Selenium,

  1. 1. is a free and open source
  2. 2. have a large user base and helping communities
  3. 3. have cross Browser compatibility (Firefox, Chrome, Internet Explorer, Safari etc.)
  4. 4. have great platform compatibility (Windows, Mac OS, Linux etc.)
  5. 5. supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
  6. 6. has fresh and regular repository developments
  7. 7. supports distributed testing

4. What is Selenium? What are the different Selenium components?

Ans:

Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web-based applications and a wide range of browsers and platforms. Due to its existence in the open source community, it has become one of the most accepted tools amongst the testing professionals.

Selenium is not just a single tool or a utility, rather a package of several testing tools and for the same reason, it is referred to as a Suite. Each of these tools is designed to cater different testing and test environment requirements.

The suite package constitutes the following sets of tools:

  • Selenium Integrated Development Environment (IDE) – Selenium IDE is a record and playback tool. It is distributed as a Firefox Plugin.
  • Selenium Remote Control (RC) – Selenium RC is a server that allows a user to create test scripts in the desired programming language. It also allows executing test scripts within the large spectrum of browsers.
  • Selenium WebDriver – WebDriver is a different tool altogether that has various advantages over Selenium RC. WebDriver directly communicates with the web browser and uses its native compatibility to automate.
  • Selenium Grid – Selenium Grid is used to distribute your test execution on multiple platforms and environments concurrently.

5. What are the testing types that can be supported by Selenium?

Ans:

Selenium supports the following types of testing:

  1. 1. Functional Testing
  2. 2. Regression Testing

6. What are the limitations of Selenium?

Ans:

Following are the limitations of Selenium:

  • Selenium supports testing of only web-based applications
  • Mobile applications cannot be tested using Selenium
  • Captcha and Barcode readers cannot be tested using Selenium
  • Reports can only be generated using third-party tools like TestNG or JUnit.
  • As Selenium is a free tool, thus there is no ready vendor support through which the user can find numerous helping communities.
  • The user is expected to possess prior programming language knowledge.

7. When should I use Selenium IDE?

Ans:

Selenium IDE is the simplest and easiest of all the tools within the Selenium Package. Its record and playback feature makes it exceptionally easy to learn with minimal acquaintances to any programming language. Selenium IDE is an ideal tool for a naïve user.

8. What is Selenese?

Ans:

Selenese is the language which is used to write test scripts in Selenium IDE.

9. What are the different types of locators in Selenium?

Ans:

The locator can be termed as an address that identifies a web element uniquely within the webpage. Thus, to identify web elements accurately and precisely we have different types of locators in Selenium:

  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath
  • CSS Selector
  • DOM

10. What is the difference between assert and verify commands?

Ans:

Assert command checks whether the given condition is true or false. Let’s say we assert whether the given element is present on the web page or not. If the condition is true then the program control will execute the next test step but if the condition is false, the execution would stop and no further test would be executed.

Verify: Verify command also checks whether the given condition is true or false. Irrespective of the condition being true or false, the program execution doesn’t halt i.e. any failure during verification would not stop the execution and all the test steps would be executed.

11. What is an XPath?

Ans:

XPath is used to locate a web element based on its XML path. XML stands for Extensible Markup Language and is used to store, organize and transport arbitrary data. It stores data in a key-value pair which is very much similar to HTML tags. Both being markup languages and since they fall under the same umbrella, XPath can be used to locate HTML elements.

The fundamental behind locating elements using XPath is the traversing between various elements across the entire page and thus enabling a user to find an element with the reference of another element.

12. What is the difference between “/” and “//” in Xpath?

Ans:

Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node.

Double Slash “//” – Double slash is used to create Xpath with relative path i.e. the xpath would be created to start selection from anywhere within the document.

Subscribe For Free Demo
[contact-form-7 404 "Not Found"]

13. What is Same origin policy and how can it be handled?

Ans:

The problem of same origin policy disallows access to the DOM of a document from an origin that is different from the origin we are trying to access the document.

Origin is a sequential combination of scheme, host, and port of the URL. For example, for a URL https://www.softwaretestinghelp.com/resources/, the origin is a combination of http, softwaretestinghelp.com, 80 correspondingly.

Thus the Selenium Core (JavaScript Program) cannot access the elements from an origin that is different from where it was launched. For Example, if I have launched the JavaScript Program from “https://www.softwaretestinghelp.com”, then I would be able to access the pages within the same domain such as “https://www.softwaretestinghelp.com/resources” or “https://www.softwaretestinghelp.com/istqb-free-updates/”. The other domains like google.com, seleniumhq.org would no longer be accessible.

So, In order to handle the same origin policy, Selenium Remote Control was introduced.

14. When should I use Selenium Grid?

Ans:

Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution, testing under different environments and saving execution time remarkably.

15. What do we mean by Selenium 1 and Selenium 2?

Ans:

Selenium RC and WebDriver, in a combination, are popularly known as Selenium 2. Selenium RC alone is also referred to as Selenium 1.

16. Which is the latest Selenium tool?

Ans:

WebDriver

17. How do I launch the browser using WebDriver?

Ans:

The following syntax can be used to launch Browser:

  • WebDriver driver = new FirefoxDriver();
  • WebDriver driver = new ChromeDriver();
  • WebDriver driver = new InternetExplorerDriver();

18. What are the different types of Drivers available in WebDriver?

Ans:

The different drivers available in WebDriver are:

  • FirefoxDriver
  • InternetExplorerDriver
  • ChromeDriver
  • SafariDriver
  • OperaDriver
  • AndroidDriver
  • IPhoneDriver
  • HtmlUnitDriver

19. What are the different types of waits available in WebDriver?

Ans:

There are two types of waits available in WebDriver:

  1. 1. Implicit Wait
  2. 2. Explicit Wait

Implicit Wait: Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script. Thus, the subsequent test step would only execute when the 30 seconds have elapsed after executing the previous test step/command.

Explicit Wait: Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time has elapsed. Unlike Implicit waits, explicit waits are applied for a particular instance only.

20. How to type in a textbox using Selenium?

Ans:

The user can use sendKeys(“String to be entered”) to enter the string in the textbox.

Syntax:

  • WebElement username = drv.findElement(By.id(“Email”));
  • // entering username
  • username.sendKeys(“sth”);

21.How can you find if an element is displayed on the screen?

Ans:

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.

  1. 1. isDisplayed()
  2. 2. isSelected()
  3. 3. isEnabled()

Syntax:

isDisplayed():

  • boolean buttonPresence = driver.findElement(By.id(“gbqfba”)).isDisplayed();

isSelected():

  • boolean buttonSelected = driver.findElement(By.id(“gbqfba”)).isSelected();

isEnabled():

  • boolean searchIconEnabled = driver.findElement(By.id(“gbqfb”)).isEnabled();

22. How can we get a text of a web element?

Ans:

Get command is used to retrieve the inner text of the specified web element. The command doesn’t require any parameter but returns a string value. It is also one of the extensively used commands for verification of messages, labels, errors etc displayed on the web pages.

Syntax:

  • String Text = driver.findElement(By.id(“Text”)).getText();

23. How to select value in a dropdown?

Ans:

The value in the dropdown can be selected using WebDriver’s Select class.

Syntax:

selectByValue:

  • Select selectByValue = new Select(driver.findElement(By.id(“SelectID_One”)));
  • selectByValue.selectByValue(“greenvalue”);

selectByVisibleText:

  • Select selectByVisibleText = new Select (driver.findElement(By.id(“SelectID_Two”)));
  • selectByVisibleText.selectByVisibleText(“Lime”);

selectByIndex:

  • Select selectByIndex = new Select(driver.findElement(By.id(“SelectID_Three”)));
  • selectByIndex.selectByIndex(2);

24. What are the different types of navigation commands?

Ans:

Following are the navigation commands:

navigate().back() – The above command requires no parameters and takes back the user to the previous webpage in the web browser’s history.

Sample code:

  • driver.navigate().back();

navigate().forward() – This command lets the user to navigate to the next web page with reference to the browser’s history.

Sample code:

  • driver.navigate().forward();

navigate().refresh() – This command lets the user to refresh the current web page there by reloading all the web elements.

Sample code:

  • driver.navigate().refresh();

navigate().to() – This command lets the user to launch a new web browser window and navigate to the specified URL.

Sample code:

  • driver.navigate().to(“https://google.com”);

25. How to click on a hyperlink using linkText?

Ans:

  • driver.findElement(By.linkText(“Google”)).click();

The command finds the element using link text and then click on that element and thus the user would be redirected to the corresponding page.

The above-mentioned link can also be accessed by using the following command.

  • driver.findElement(By.partialLinkText(“Goo”)).click();

The above command finds the element based on the substring of the link provided in the parenthesis and thus partialLinkText() finds the web element with the specified substring and then clicks on it.

26. How to handle frames in WebDriver?

Ans:

An inline frame acronym as iframe is used to insert another document within the current HTML document or simply a web page into a web page by enabling nesting.

Select iframe by id

  • driver.switchTo().frame(“ID of the frame“);

Locating iframe using tagName

  • driver.switchTo().frame(driver.findElements(By.tagName(“iframe”).get(0));

Locating iframe using index

frame(index)

  • driver.switchTo().frame(0);

frame(Name of Frame)

  • driver.switchTo().frame(“name of the frame”);

frame(WebElement element)

Select Parent Window

  • driver.switchTo().defaultContent();

27. When do we use findElement() and findElements()?

Ans:

findElement(): findElement() is used to find the first element in the current web page matching to the specified locator value. Take a note that only first matching element would be fetched.

Syntax:

  • WebElement element = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));

findElements(): findElements() is used to find all the elements in the current web page matching to the specified locator value. Take a note that all the matching elements would be fetched and stored in the list of WebElements.

Syntax:

  • List <WebElement> elementList = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));

28.How to find more than one web element in the list?

Ans:

At times, we may come across elements of the same type like multiple hyperlinks, images etc arranged in an ordered or unordered list. Thus, it makes absolute sense to deal with such elements by a single piece of code and this can be done using WebElement List.

Sample Code

  • // Storing the list
  • List <WebElement> elementList = driver.findElements(By.xpath(“//div[@id=’example’]//ul//li”));
  • // Fetching the size of the list
  • int listSize = elementList.size();
  • for (int i=0; i<listSize; i++)
  • {
  • // Clicking on each service provider link
  • serviceProviderLinks.get(i).click();
  • // Navigating back to the previous page that stores link to service providers
  • driver.navigate().back();
  • }

29. What is the difference between driver.close() and driver.quit command?

Ans:

close(): WebDriver’s close() method closes the web browser window that the user is currently working on or we can also say the window that is being currently accessed by the WebDriver. The command neither requires any parameter nor does it return any value.

quit(): Unlike close() method, quit() method closes down all the windows that the program has opened. Same as close() method, the command neither requires any parameter nor does it return any value.

30. Can Selenium handle windows based pop up?

Ans:

Selenium is an automation testing tool which supports only web application testing. Therefore, windows pop up cannot be handled using Selenium.

31. How can we handle web-based pop-up?

Ans:

WebDriver offers the users a very efficient way to handle these pop-ups using Alert interface. There are the four methods that we would be using along with the Alert interface.

  • void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop-up window appears.
  • void accept() – The accept() method clicks on the “Ok” button as soon as the pop-up window appears.
  • String getText() – The getText() method returns the text displayed on the alert box.
  • void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.

Syntax:

  • // accepting javascript alert
  •              Alert alert = driver.switchTo().alert();
  • alert.accept();

32. How to assert the title of the web page?

Ans:

To verify the title of the web page

  • assertTrue(“The title of the window is incorrect.”,driver.getTitle().equals(“Title of the page”));

33. How to mouse hover on a web element using WebDriver?

Ans:

WebDriver offers a wide range of interaction utilities that the user can exploit to automate mouse and keyboard events. Action Interface is one such utility which simulates the single user interactions.

Thus, In the following scenario, we have used Action Interface to mouse hover on a drop down which then opens a list of options.

Sample Code:

  • // Instantiating Action Interface
  • Actions actions=new Actions(driver);
  • // howering on the dropdown
  • actions.moveToElement(driver.findElement(By.id(“id of the dropdown”))).perform();
  • // Clicking on one of the items in the list options
  • WebElement subLinkOption=driver.findElement(By.id(“id of the sub link”));
  • subLinkOption.click();

34. How to retrieve CSS properties of an element?

Ans:

The values of the css properties can be retrieved using a get() method:

Syntax:

  • driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
  • driver.findElement(By.id(“id“)).getCssValue(“font-size”);

35. How to capture a screenshot in WebDriver?

Ans:

  • 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 CaptureScreenshot {
  • WebDriver driver;
  • @Before
  • public void setUp() throws Exception {
  • driver = new FirefoxDriver();
  • driver.get(“https://google.com”);
  • }
  • @After
  • public void tearDown() throws Exception {
  • driver.quit();
  • }
  •  
  • @Test
  • public void test() throws IOException {
  • // Code to capture the screenshot
  • File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
  • // Code to copy the screenshot in the desired location
  • FileUtils.copyFile(scrFile, new File(“C:\\CaptureScreenshot\\google.jpg”))
  • }
  • }
Course Curriculum

Get On-Demand Selenium Training & Become An Expert Selenium Tester

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

36. What is Junit?

Ans:

Junit is a unit testing framework introduced by Apache. Junit is based on Java.

37. What are Junit annotations?

Ans:

Following are the JUnit Annotations:

  • @Test: Annotation lets the system know that the method annotated as @Test is a test method. There can be multiple test methods in a single test script.
  • @Before: Method annotated as @Before lets the system know that this method shall be executed every time before each of the test methods.
  • @After: Method annotated as @After lets the system know that this method shall be executed every time after each of the test methods.
  • @BeforeClass: Method annotated as @BeforeClass lets the system know that this method shall be executed once before any of the test methods.
  • @AfterClass: Method annotated as @AfterClass lets the system know that this method shall be executed once after any of the test methods.
  • @Ignore: Method annotated as @Ignore lets the system know that this method shall not be executed.

38. What is TestNG and how is it better than Junit?

Ans:

TestNG is an advanced framework designed in a way to leverage the benefits by both the developers and testers. With the commencement of the frameworks, JUnit gained enormous popularity across the Java applications, Java developers and Java testers with remarkably increasing the code quality. Despite being easy to use and straightforward, JUnit has its own limitations which give rise to the need of bringing TestNG into the picture. TestNG is an open source framework which is distributed under the Apache Software License and is readily available for download.

TestNG with WebDriver provides an efficient and effective test result format that can, in turn, be shared with the stakeholders to have a glimpse on the product’s/application’s health thereby eliminating the drawback of WebDriver’s incapability to generate test reports. TestNG has an inbuilt exception handling mechanism which lets the program to run without terminating unexpectedly.

There are various advantages that make TestNG superior to JUnit. Some of them are:

  • Added advance and easy annotations
  • Execution patterns can set
  • Concurrent execution of test scripts
  • Test case dependencies can be set

39.How to set test case priority in TestNG?

Ans:

Setting Priority in TestNG

Code Snippet

  • package TestNG;
  • import org.testng.annotations.*;
  • public class SettingPriority {
  • @Test(priority=0)
  • public void method1() {
  • }
  • @Test(priority=1)
  • public void method2() {
  • }
  • @Test(priority=2)
  • public void method3() {
  • }
  • }

Test Execution Sequence:

  1. 1. Method1
  2. 2. Method2
  3. 3. Method3

40. What is a framework?

Ans:

The framework is a constructive blend of various guidelines, coding standards, concepts, processes, practices, project hierarchies, modularity, reporting mechanism, test data injections etc. to pillar automation testing.

41. What are the advantages of the Automation framework?

Ans:

The advantage of Test Automation framework

  • Reusability of code
  • Maximum coverage
  • Recovery scenario
  • Low-cost maintenance
  • Minimal manual intervention
  • Easy Reporting

42. What are the different types of frameworks?

Ans:

Below are the different types of frameworks:

  1. 1. Module Based Testing Framework: The framework divides the entire “Application Under Test” into the number of logical and isolated modules. For each module, we create a separate and independent test script. Thus, when these test scripts have been taken together builds a larger test script representing more than one module.
  2. 2. Library Architecture Testing Framework: The basic fundamental behind the framework is to determine the common steps and group them into functions under a library and call those functions in the test scripts whenever required.
  3. 3. Data Driven Testing Framework: Data Driven Testing Framework helps the user segregate the test script logic and the test data from each other. It lets the user store the test data into an external database. The data is conventionally stored in “Key-Value” pairs. Thus, the key can be used to access and populate the data within the test scripts.
  4. 4. Keyword Driven Testing Framework: The Keyword Driven testing framework is an extension to Data-driven Testing Framework in a sense that it not only segregates the test data from the scripts, it also keeps the certain set of code belonging to the test script into an external data file.
  5. 5. Hybrid Testing Framework: Hybrid Testing Framework is a combination of more than one above mentioned frameworks. The best thing about such a setup is that it leverages the benefits of all kinds of associated frameworks.
  6. 6. Behavior Driven Development Framework: Behavior Driven Development framework allows automation of functional validations in an easily readable and understandable format to Business Analysts, Developers, Testers, etc.

43. How can I read test data from excels?

Ans:

Test data can efficiently be read from excel using JXL or POI API.

44. What is the difference between POI and jxl jar?

Ans:

JXL jarPOI jar
JXL supports “.xls” format i.e. binary based format. JXL doesn’t support Excel 2007 and “.xlsx” format i.e. XML based formatPOI jar supports all of these formats
JXL API was last updated in the year 2009POI is regularly updated and released
The JXL documentation is not as comprehensive as that of POIPOI has a well prepared and highly comprehensive documentation
JXL API doesn’t support rich text formattingPOI API supports rich text formatting
JXL API is faster than POI APIPOI API is slower than JXL API

45. Can WebDriver test Mobile applications?

Ans:

WebDriver cannot test Mobile applications. WebDriver is a web-based testing tool, therefore applications on the mobile browsers can be tested.

46. Can captcha be automated?

Ans:

No, captcha and barcode readers cannot be automated.

47. What is an Object Repository? How can we create an Object Repository in Selenium?

Ans:

Object Repository is a term used to refer to the collection of web elements belonging to Application Under Test (AUT) along with their locator values. Thus, whenever the element is required within the script, the locator value can be populated from the Object Repository. Object Repository is used to store locators in a centralized location instead of hardcoding them within the scripts.

In Selenium, objects can be stored in an excel sheet which can be populated inside the script whenever required.

48. How do you locate an element by partially comparing its attributes in XPath?

Ans:

XPath supports the contains() method. It allows partial matching of an attribute’s value.

It helps when the attributes use dynamic values while having some fixed part.

See the below example-

  • xPath usage => //*[contains(@category, ‘tablet’)]

The above expression would match all values of the category attribute having the word ‘tablet’ in them.

49. How do you locate elements based on the text in XPath?

Ans:

We can call the text() method. The below expression will get elements that have text nodes that equal ‘Python.’

  • xPath usage = //*[text()=’Python’]

50. How do you access the parent of a node with XPath?

Ans:

We can use the double dot (“..”) to point to the parent of any node using the XPath.

For example – The locator //span[@id=”current”]/.. will return the parent of the span element matching id value as ‘current’.

51. How do you get to the nth sub-element using the XPath?

Ans:

We can modify the XPath expression to get to the nth element in the following ways:

1. Use XPath as an array by appending the square brackets with an index.

Example

  • tr[2]

The above XPath expression will return the second row of a table.

2. By calling position() in the XPath expression

Example

  • tr[position()=4]

The above XPath will give the fourth row.

52. How do you use “class” as a CSS selector?

Ans:

We can use the below syntax to access elements using the class CSS selector.

  • .<class>
  • e.g. .color

It can help to select all elements related to the specified class.

53. How do you use “ID” as a CSS selector?

Ans:

We can use the below syntax to access elements using ID as the CSS selector.

  • #<ID>

Example

  • #name

54. How to specify attribute value while using the CSS selector?

Ans:

Here is the syntax to provide the attribute value with the CSS selector.

  • [attribute=value]

Example

  • [type=submit]

55. How to access the nth element using the CSS selector?

Ans:

Here is the syntax to access the nth attribute using the CSS selector.

  • <type>:nth-child(n)

Example

  • tr:nth-child(4)
Course Curriculum

Best JOB Oriented Selenium Certification Training from Real-Time Experts

Weekday / Weekend BatchesSee Batch Details

56. What is the primary difference between the XPath and CSS selectors?

Ans:

With the XPath, we can traverse both forward and backward, whereas CSS selector only moves forward.

57. What are the steps to create a simple Web Driver script?

Ans:

Below are the minimal steps to create a WebDriver script.

  • Launch the Firefox or Chrome browser by creating the WebDriver object.
  • Open website www.google.co.in using the get() method.
  • Wait for the web page to load.
  • Display a message on the console that the webpage gets loaded successfully.
  • Close the browser.

Source Code:

  • import java.util.concurrent.TimeUnit;
  • import org.openqa.selenium.WebDriver;
  • import org.openqa.selenium.firefox.FirefoxDriver;
  • public class SimpleWebDriverScript {
  •     public static void main(String[] args) {
  •         WebDriver driver = new FirefoxDriver();
  •         String URL = “https://www.google.co.in”;
  •         driver.get(URL);
  •         driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
  •         System.out.println(“Webpage gets loaded successfully!!”);
  •         driver.close();
  •   }
  • }

58. What does FirefoxDriver mean, a Class or an Interface?

Ans:

FirefoxDriver is a Java class, and it implements the WebDriver interface.

59. Which is the super interface of Selenium Web Driver?

Ans:

The SearchContext acts as the super interface for the Web Driver. It is the external interface which has only two methods:

  1. 1. findElement()
  2. 2. findElements()

60. What does the Webdriver driver = new FirefoxDriver(); mean?

Ans:

  • Webdriver driver = new FirefoxDriver();

The above line of code represents the following:

  • The driver is a variable of type ‘Webdriver’ interface.
  • We are instantiating an object of the FirefoxDriver class and storing it into the driver variable.

61. Why do we create a reference variable of type Webdriver, not the actual browser type?

Ans:

It is because we could use the same Webdriver variable to hold the object of any browser, such as the ChromeDriver, IEDriver, or SafariDriver, etc.

We follow this approach as it can work with any browser instance.

  • WebDriver driver = new FirefoxDriver();

This approach is right too but will work only the Firefox.

  • FirefoxDriver driver = new FirefoxDriver();

62. How do you pass credentials to an authentication popup in Selenium?

Ans:

We combine the username and password strings using the colon separator and stuff them between the “http://” and the site URL. See the below example.

e.g. http://userid:passcode@somesite.com

63. What are the different exceptions available in Selenium?

Ans:

Like many programming languages, Selenium also provides exception handling. The standard exceptions in Selenium are as follows.

  • TimeoutException: This occurs if a command doesn’t finish within the specified duration.
  • NoSuchElementException: This occurs if the web element with the specified attributes is not present on the page.
  • ElementNotVisibleException: This occurs if the element is not visible but still there inside the DOM.
  • StaleElementException: This occurs in the absence of an element that either got deleted or detached from the DOM.

64. What do you know about an exception test in Selenium?

Ans:

An exception test is a special exception that occurs in a test class.

Suppose, we have created a test case that can throw an exception.

In this case, the @Test annotation can help us specify the exception that could occur.

Check out from the below example.

  • @Test(actualException = ElementNotVisibleException.class)

65. How is an Assert different from Verify?

Ans:

  1. 1. Assert: It allows us to verify the result of an expression or an operation. If the “assert” fails, then it will abort the test execution and continue with the next case.
  2. 2. Verify: It also operates the same as the assert does. However, if the “verify” fails, then it won’t abort the test instead continue with the next step.

66. What difference do you make between Soft vs. Hard Assert in Selenium?

Ans:

  • Soft Assert: It aggregates the errors that occurred during the test execution. If such an assert fails, the control jumps to the next step.
  • Hard Assert: It immediately responds with an AssertException and breaks the current test. After that, the next case in the sequence gets executed.

67. What are the different waits available in WebDriver?

Ans:

In Selenium Webdriver, the following three types of wait mechanisms are available.

  1. 1. Implicit Wait – Click to view.
  2. 2. Explicit Wait – Click to view.
  3. 3. Fluent Wait – Click to view.

68. What is Web Driver Implicit wait?

Ans:

Implicit Wait: It is a wait timeout which applies to a Webdriver instance.  It implies that all actions of this instance will timeout only after waiting for a duration specified by the implicit wait.

  • WebDriver driver = new ChromeDriver();
  • driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

69. What is Web Driver Explicit wait?

Ans:

Explicit Wait: It is an exclusive timeout method that works by adding code to delay the execution until a specific condition arises. It is more customizable in terms that we can set it up to wait for any suitable situation. Usually, we use a few of the pre-built Expected Conditions to wait for elements to become clickable, visible, invisible, etc.

  • WebDriver driver = new ChromeDriver();
  • driver.get(“http://target_page_url”);
  • WebElement dynamicElement = (new WebDriverWait(driver, 15))
  •  .until(ExpectedConditions.presenceOfElementLocated(By.id(“dynamicElement”)));

70. What is the command to enter text in the HTML text box using Selenium?

Ans:

We can do so by using the sendKeys() method.

  • WebDriver webdriver = new FirefoxDriver();
  • webdriver.get(“https://www.google.com”);
  • webdriver.findElement(By.xpath(“<<xpath expr>>”)).sendKeys(“Selenium Interview Questions”);

71. How to enter text in the HTML text box without invoking the sendKeys()?

Ans:

There is a Selenium JavascriptExecutor class that provides methods to perform actions on the HTML elements.

  • // Set up the JS object
  • JavascriptExecutor jscript = (JavascriptExecutor)webdriver;
  • // Issue command to enter the text
  • jscript.executeScript(“document.getElementById(‘textbox’).value = ‘Some Text’;”);

72. What is the method to read the JavaScript variable using Selenium WebDriver?

Ans:

Again, we can utilize the JavascriptExecutor class to read the value of a JS variable. See the below code.

  • // Set up the JavaScript object
  • JavascriptExecutor jscript = (JavascriptExecutor) webdriver;
  • // Read the site title
  • String strTitle = (String)jscript.executeScript(“return document.title”);
  • System.out.println(“Webpage Title: ” + strTitle);

73. What is the command to reset the HTML text box in Selenium Webdriver?

Ans:

Selenium provides the clear() function to reset the value inside the text element.

  • WebDriver webdriver = new FirefoxDriver();
  • webdriver.get(“https://www.google.com”);
  • webdriver.findElement(By.xpath(“<<xpath expr>>”)).sendKeys(“Selenium Interview Questions”);
  • webdriver.findElement(By.xpath(“<<xpath expr>>”)).clear();

74. What is the command to get the value of a text box in Selenium Webdriver?

Ans:

Selenium provides the getText() function to read the value inside the text element.

  • package webdriverdemo;
  • import org.openqa.selenium.By;
  • import org.openqa.selenium.WebDriver;
  • import org.openqa.selenium.chrome.ChromeDriver;
  • import org.testng.annotations.Test;
  • public class demoClass {
  •  @Test
  •  public void readText() {
  •     System.setProperty(“webdriver.chrome.driver”, “<<chromedriver.exe>>”);
  •     WebDriver webdriver = new ChromeDriver();
  •     webdriver.get(“https://www.google.com”);
  •     String strText = webdriver.findElement(By.xpath(“<<xpath expr>>”)).getText();
  •     System.out.println(“Text element contains: ” + strText);
  •  }
  • };

75. What is the command to get the attribute value in Selenium Webdriver?

Ans:

Selenium provides the getAttribute(value) function to read the value inside the text element.

  • String strValue = webdriver.findElement(By.name(“<<attrname>>”)).getAttribute(“value”);
  • System.out.println(“Attribute value is: ” + strValue);
selenium Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

76. What is the command to click on a hyperlink in Selenium Webdriver?

Ans:

Selenium provides the click() function to click on a HTML link.

  • webdriver.findElement(By.linkText(“Selenium Interview Questions”)).click();

77. What is the command to submit the HTML form in Selenium Webdriver?

Ans:

Selenium provides the submit() function to finalize a HTML form.

  • webdriver.findElement(By.id(“<<htmlform>>”)).submit();

However, we can also achieve the same effect by calling the click() method.

78. What is the command to press enter inside the HTML text box using Selenium Webdriver?

Ans:

Selenium provides Enum Key macros to simulate the enter action.

  • webdriver.findElement(By.xpath(“<<xpath>>”)).sendKeys(Keys.ENTER);

79. What is the Selenium command to delay test execution for 10 seconds?

Ans:

In Java, we can use the following method to halt the execution for a specified no. of milliseconds.

  • java.lang.Thread.sleep(long milliseconds)

To halt for 10 seconds, we can issue the following command:

  • Thread.sleep(10000)

80. Is it mandatory to prefix the URL with HTTP or HTTPS while calling the web driver’s get() method?

Ans:

Yes, if the URL doesn’t contain the HTTP prefix, then the program will throw an exception.

Hence, it is mandatory to pass the HTTP or HTTPS protocol while calling the web driver’s get() method.

81. What is the other method which gives the same effect as we get from the web driver’s get()?

Ans:

Selenium provides the “navigate.to(link)” method. It does the same thing as we achieve from the get() call.

82. What is the principal difference between “GET” and “NAVIGATE” methods?

Ans:

Get method makes a page to load or extracts its source or parse the full text. On the contrary, the navigate method tracks the history and can perform operations like refresh, back, and forward.

For example, We like to move forward, execute some functionality and then move back to the home page.

We can achieve this by calling the Selenium’s navigate() API.

  • The driver.get() method waits until the page finish loading.
  • The driver.navigate() will only redirect and return immediately.

83. How can I move back and forth in a browser using Selenium?

Ans:

Selenium provides the following methods for moving back and forth in a browser.

  1. 1. navigate().forward() – to move to the next web page as per the browser’s history
  2. 2. navigate().back() – to move back to the previous page as per the browser’s history
  3. 3. navigate().refresh() – to reload the current page
  4. 4. navigate().to(“URL”) – to start a new browser window and opening up the specified link

84. What is the Selenium command to fetch the current page URL?

Ans:

To retrieve the current page URL, we can call the getCurrentURL() function.

  • webdriver.getCurrentUrl();

85. What is the Selenium command to set the browser maximized?

Ans:

We can maximize the browser window by calling Selenium’s maximize() method. It sets the current window in the maximized state.

  • webdriver.manage().window().maximize();

86. What is the Selenium command to delete session cookies?

Ans:

To delete session cookies, we can invoke the deleteAllCookies() method.

  • webdriver.manage().deleteAllCookies();

87. State the difference between Web driver’s getWindowHandle() and getWindowHandles() methods?

Ans:

webdriver.getWindowHandle() – It gets the handle of the active web page.

webdriver.getWindowHandles() – It gets the list of handles for all the pages opened at a time.

88. State the difference between Web driver’s close() and quit() methods?

Ans:

These two methods perform the same task, i.e., the closing of the browser. However, there is a slight difference.

webdriver.close(): It closes the active WebDriver instance.

webdriver.quit(): It closes all the WebDriver instances opened at a time.

89. State the difference between Web driver’s findElement() and findElements() methods?

Ans:

Both these methods traverse the DOM looking for the target web element. However, there are some basic differences between them.

1. The findElement() method returns the first WebElement matching the locator, whereas the findElements() fetches all passing the locator criteria.

// Syntax of findElement()

  • WebElement item = webdriver.findElement(By.id(“<<ID value>>”));

// Syntax of findElements()

  • List <WebElement> items = webdriver.findElements(By.id(“<<ID value>>”));

2. Another difference is if no element is matched, then the findElement() raises 90NoSuchElementException whereas findElements() returns an empty list.

90. How do you check if an object is present on multiple pages?

Ans:

We can use the isElementPresent() command to verify the object on all pages.

  • assertTrue(selenium.isElementPresent(locator));

91. How do you check for the presence of a web element after the successful page load?

Ans:

We can verify the presence of a web element with the following code.

While using the below function, do supply some timeout value (in seconds) to check the element in a regular interval.

  • public void checkIfElementPresent(String element, int timeout) throws Exception {
  •     for (int sec = 0;; sec++) {
  •         if (sec >= timeout)
  •             fail(“Timeout! Couldn’t locate element.” + element);
  •         try {
  •             if (selenium.isElementPresent(element))
  •                 break;
  •         } catch (Exception ex) {
  •         }
  •         Thread.sleep(1000);
  •     }
  • }

92. How to handle Web-based alerts/pop-ups in Selenium?

Ans:

WebDriver exposes the following APIs to handle such popups.

  • Dismiss(): It handles the alert by simulating the Cancel button.
  • Accept(): It handles the alert window by simulating the Okay button.
  • GetText(): You may call it to find out the text shown by the alert.
  • SendKeys(): This method simulates keystrokes in the alert window.

93. How to handle AJAX controls using Selenium?

Ans:

Let’s understand the handling of AJAX with an example.

Consider the Google search text box, which is an Ajax control. Whenever we write some text into the box, it shows up a list of auto-suggested values.

To automate this type of element, we need to grab the above list in a string as soon as the box receives input. After that, we can split and take the values one by one.

94. How to work with AJAX controls in WebDriver?

Ans:

AJAX is an acronym for Asynchronous JavaScript and XML. It is independent of the opening and closing tags required for creating valid XML.

Sometimes, the WebDriver itself manages to work with the Ajax controls and actions. However, if it doesn’t succeed, then try out the below code.

  • //Waiting for Ajax Control
  • WebElement AjaxCtrl = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By. &lt;locatorType&gt;(“&lt;locator Value&gt;”)));

95. What is a Page Object in Selenium WebDriver?

Ans:

First of all, both these terms belong to the Page Object Model (POM), a design pattern in Selenium. Let’s now see how they are different from each other.

Page Object is a class in POM corresponding to a web page. It captures the functionality as functions and objects as members.

  • public class LogInPage
  • {
  •     private WebElement user;
  •     private WebElement pass;
  •     public LogInPage() {
  •     }
  •     public void findObjects() {
  •         user = browser.findElement(By.id(“userName”));
  •         pass = browser.findElement(By.id(“password”));
  •     }
  •     public void processLogIn() {
  •         user.sendKeys(“john”);
  •         pass.sendKeys(“password”);
  •     }
  • }

96. What is a Page Factory in Selenium WebDriver?

Ans:

Page Factory is a method to set up the web elements within the page object.

  • public class LogInPage
  • {
  •     @FindBy(id=”userName”)
  •     private WebElement user;
  •     @FindBy(id=”password”)
  •     private WebElement pass;
  •     public LogInPage() {
  •         PageFactory.initElements(browser, this); // Setup the members as browser.findElement()
  •     }
  •     public void processLogIn() {
  •         user.sendKeys(“john”);
  •         pass.sendKeys(“password”);
  •     }
  • }

97. What are User Extensions, and how do you create them?

Ans:

User extensions are a set of functions written in JavaScript. They are present in a separate known as the extension file. Selenium IDE or Selenium RC access it to activate the extensions.

Selenium’s core has a JavaScript codebase. So, we can also use it to create the extension.

The extension has a specific format, as given below.

  • // sample
  • Selenium.prototype.doFunctionName = function(){
  • }

The function name begins with a “do” prefix. It signals Selenium to interpret this function as a command.

It means we can call the above function inside any of our steps.

98. How to simulate Mouse over action on a submenu option under a header menu?

Ans:

Using the Actions object, you can first move the menu title, and then proceed to the popup menu item and click it. Don’t at all miss to invoke the “actions.Perform()” at the end. Check out the below Java code:

  • Actions acts = new Actions(driver);
  • WebElement menuHoverLink = driver.findElement(By.linkText(“Menu heading”));
  • acts.moveToElement(menuHoverLink);
  • WebElement subLink = driver.findElement(By.cssSelector(“#headerMenu .subLink”));
  • acts.moveToElement(subLink);
  • acts.click();
  • acts.perform();

99. How to resolve the SSL certificate issue (secured connection error) in Firefox with WebDriver?

Ans:

There can be many reasons for the secured connection error. It could be because of the following:

  • While a site is getting developed, it may not have the right SSL certificate.
  • The site may be using a self-signed certificate.
  • The SSL may not have configured appropriately at the server end.

However, you still want to test the site’s standard functionality using Selenium. Then, the idea is to switch off the SSL setting and ignore the SSL error.

Check out the below code to disable the SSL in Selenium.

  • FirefoxProfile ssl = new FirefoxProfile();
  • ssl.setAcceptUntrustedCertificates(true);
  • ssl.setAssumeUntrustedCertificateIssuer(false);
  • WebDriver ins = new FirefoxDriver(ssl);

100. How to handle a proxy using Selenium in Java?

Ans:

Selenium implements a PROXY class to configure the proxy. See below example:

  • String setPROXY = “10.0.0.10:8080”;
  • org.openqa.selenium.Proxy allowProxy = new.org.openqa.selenium.Proxy();
  • allowProxy.setHTTPProxy(setPROXY)
  •           .setFtpProxy(setPROXY)
  •           .setSslProxy(setPROXY);
  • DesiredCapabilities allowCap = new DesiredCapabilities();
  • allowCap.setCapability(CapabilityType.PROXY, allowProxy);
  • WebDriver driver = new FirefoxDriver(allowCap);

101. What is the difference between Selenium and QTP?

Ans:

FeatureSeleniumQuick Test Professional (QTP)
Browser CompatibilitySelenium supports almost all the popular browsers like Firefox, Chrome, Safari, Internet Explorer, Opera etcQTP supports Internet Explorer, Firefox and Chrome. QTP only supports Windows Operating System
DistributionSelenium is distributed as an open source tool and is freely availableQTP is distributed as a licensed tool and is commercialized
Application under TestSelenium supports testing of only web based applicationsQTP supports testing of both the web based application and windows based application
Object RepositoryObject Repository needs to be created as a separate entityQTP automatically creates and maintains Object Repository
Language SupportSelenium supports multiple programming languages like Java, C#, Ruby, Python, Perl etcQTP supports only VB Script
Vendor SupportAs Selenium is a free tool, user would not get the vendor’s support in troubleshooting issuesUsers can easily get the vendor’s support in case of any issue

Are you looking training with Right Jobs?

Contact Us

Popular Courses