30+ Most Popular Selenium Interview Questions And Answers

Are you getting ready for a Selenium interview? If yes, then it’s important to refresh your knowledge on common Selenium interview questions

In this article we will provide you the comprehensive list of Selenium interview questions and answers.

Selenium Interview Questions

Table of Contents

Basic & Advanced Selenium Interview Questions

Whether you are experienced or a freshers, doesn’t matter here we have included Selenium interview questions which is commonly asked.

1. What is Selenium?

Selenium is the open source tool which is used to automate the web based applications or browser-based applications, It is easy to use and supports various programming languages such as Java, Python, C#, Ruby, PHP etc.

2. What are the main components of Selenium?

Selenium has mainly four components, below are the details

  • Selenium IDE (Selenium Integrated Development Environment) – It is the Firefox plugin which allow us to records the browser action and playback the scripts.
  • Selenium RC (Selenium Remote Control) – It is known as Selenium 1. It allowed us to write automated browser based application tests in several programming languages like Java, C#, Python, etc.
  • Selenium WebDriver – Selenium WebDriver is a Open-Source Framework for automating browsers based applications. It supports Java, C#, PHP, Python, Perl, Ruby.
  • Selenium Grid –  It allows us to run multiple tests on different machines and browsers at the same time. It help us to save time when testing applications.

3. What is the difference between Selenium 3 and Selenium 4?

Selenium 3Selenium 4
It uses the JSON wire protocolIt uses the W3C standardization
Native Support for browsers like Opera and PhantomJs is present.Native Support for browsers like Opera and PhantomJs not present ( removed)
Selenium IDE was only available as a Firefox extensionSelenium IDE is available as a Firefox and Chrome extension both.
No Relative locators is presentIntroduction of Relative locators that allow testers to find elements relative to another element in the DOM

4. What are the different types of locators available in Selenium ?

In Selenium WebDriver, there are 8 different types of locators are available, below are the details with usage

1). By Id

driver.findElement(By.id(“userId”));

2). By Name

driver.findElement(By.name(“userName”));

3). By TagName

driver.findElement(By.tagName(“newbutton”)

4). By ClassName

driver.findElement(By.className("AnyClassName"));

5). By LinkText

driver.findElement(By.linkText(“Today’s deals”))

6). By Partial Link Text

driver.findElement(By.partialLinkText("Clickhere"))

7). By Xpath

driver.findElement(By.xpath("//span[contains(text(),'register here')]"))

8). By CSS

driver.findElement(By.cssSelector(“input#userName”))

5. How can we use CSS Selectors to target elements based on their attribute values ?

By using [attribute=value] in a CSS selector, we can target all elements with a specific attribute. For example css=input[name=’q’] will select any element where the ‘name’ attribute has the value ‘q’.

6. What are the changes in the locator in Selenium 4 ?

In Selenium 3 we are using traditional locators such as – Id, Name, ClassName, TagName, Link text, Partial LinkText, Xpath, CSS Selector.

In Selenium 4, we are using Relative Locators such as – above, below, Left of, Right Of, Near. below is the example of Locators that can be chained as per the latest Selenium 4 Release.

By submitLocator = RelativeLocator.with(By.tagName("button")).below(By.id("userName"))
.toRightOf(By.id("click"));

7. What is the difference between driver.findElement() and driver.findElements() commands ?

  • driver.findElement() – This command is used for finding a single Web Element on a web page, it is used to return an object of the first found element by the locator. if the element is not found then it will Throws NoSuchElementException.
    • Syntax – WebElement textbox = driver.findElement(By.id(“textBoxLocator”));
  • driver.findElements() – This command is used for finding all the Web elements in a web page specified by the locator value. if no matching element is found then It returns an empty list.
    • Syntax – List <WebElement> elements = element.findElements(By.id(“value”));

8.  What is the difference between Thread.Sleep() and selenium.setSpeed() ?

  • Thread.Sleep(): This method used to pause execution of current thread for a specified period of time.
  • selenium.setSpeed():setSpeed sets a speed that will apply a delay time before every Selenium operation.

9. What is the difference between Assert and Verify in Selenium?

  • Assert: In simple term we can say, if the assert condition is true then the program control will execute the next test step but if the condition is false, the execution will stop and no further test step will be executed.
  • Verify: In simple term we can say, if the verify condition is true or false that doesn’t matter, test execution will not be halt. if will execute all the test step.

10. How to handle Stale Element Reference exceptions in Selenium ?

The stale element exception occurs when the element is not present i.e destroyed and recreated again in DOM. When this happens it means that the reference of the element in the DOM becomes stale. This Exception can be handled in various ways.

  1. Refresh the page and try to locate the stale element again.
  2. Use Explicit wait to ignore the stale element exception.
  3. Try to access the element several times in the loop(Which is usually not recommended.)

11. What are the some common Exceptions Occurred in Selenium ?

Below are the list of some common exceptions occurred in selenium.

1)ElementNotInteractableException

This Selenium exception is raised when a DOM element is displayed but can not be interacted with.

2)ElementNotSelectableException

When an element is displayed in the DOM but is not available for selection, hence is not interactable.

3)RemoteDriverServerException

This Selenium exception is raised when a server fails to reply as a result of improperly stated capabilities.

4)TimeoutException

This exception is thrown when there is not enough time for a command to be completed.

5)WebDriverException

This exception takes place when the WebDriver is trying to perform some action right after you close the browser.

Some other exceptions we usually face are as follows:

  • IllegalStateException
  • NoAlertPresentException
  • NoSuchWindowException
  • NoSuchElementException

12. What is the difference between getText() and getAttribute() Methods ?

getText() method returns the text of particular web element present on the web page by ignoring the leading and trailing spaces, on the other hand the getAttribute() method returns the value of the attribute defined in the HTML tag.

13. What are the ways to refresh a browser using Selenium WebDriver ?

There are multiple ways to refresh a page in selenium

1)driver.navigate().refresh()
2)driver.get(driver.getCurrentUrl())
3)driver. findElement(By.id(“id”)).sendKeys(Keys.F5);
4)driver.navigate().to(driver.getCurrentUrl())

14. What is the difference between driver.close() and driver.quit() methods?

The main purpose of these two methods (driver.close and driver.quit) is almost similar. Both allow us to close a browser but below is the main difference.

driver.close() - To close current WebDriver instance and make session-id invalid or expired.
driver.quit() - To close all the opened WebDriver instances and the sessionId becomes null

15. What is the difference between driver.getWindowHandle() and driver.getWindowHandles() in Selenium WebDriver?

driver.getWindowHandle() – It returns a window handle of the current page (a unique identifier)
driver.getWindowHandles() – It returns a set of window handles of the all the pages available.

16. What is the alternative to driver.get() method to open an URL using Selenium WebDriver?

Alternative method we can use as driver.navigate.to(“url”).

17. What is the difference between driver.get() and driver.navigate.to(“url”)?

driver.get(): It opens an URL and then it will wait till the whole page gets loaded
driver.navigate.to(): It navigate to an URL and then it will not wait till the whole page gets loaded

18. How to fetch the current page URL in Selenium?

In order to fetch the current URL of web page, we use getCurrentURL() method, below is the usage example

driver.getCurrentUrl();

19. How can we maximize browser window in Selenium?

In order to maximize browser window of browser in selenium we use maximize() method. This method help us to maximizes the current window if it is not already maximized.

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

20. How to delete cookies in Selenium?

In order to delete cookies we use deleteAllCookies() method present in selenium

driver.manage().deleteAllCookies();

21. How to select a value from the Dropdown?

By using Select class.

WebElement mySelectElement = driver.findElement(By.name("dropdownname"));
Select dropdown = new Select(mySelectElement);
dropdown.selectByVisibleText(Text);
dropdown.selectByIndex(Index);
dropdown.selectByValue(Value);

22. How do select values from the multi-select Dropdown?

The select class has a method named as “isMultiple()“.

Select multiSelection = new Select(driver.findElement(By.xpath(//*[@id='City']);
if(multiSelection.isMultiple()){
//Selecting multiple values by index
oSel.selectByIndex(1);
oSel.selectByIndex(2);
}

23. How to deselect an already selected value?

Select class has inbuild method of deselect the value similar to select a value method, below is the example usage

Select select = new Select(driver.findElement(By.id("oldSelectMenu")));
//Deselect option with text "Africa"
select.deselectByVisibleText("Africa");

24. How To Scroll Web Page Using Selenium WebDriver?

By using the JavaScriptExecutor interface scroll operations can be handled, below is the example usage

driver.navigate().to("https://www.mautomationsoup.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500)", "");

25. How To Scroll Web Page Down Or UP Using Selenium WebDriver?

 public  void ScrollByPixel()
{
JavascriptExecutor js = (JavascriptExecutor) Driver;
js.executeScript("window.scrollTo(0, -document.body.scrollHeight)");
}

26. How to upload files using Selenium Webdriver?

1). By using the Send Keys Method

element.sendKeys("pathofImage");

2). By Using the Robot Class.

StringSelection SelectStr = new StringSelection("ImagePath");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(SelectStr, null);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}

27. How to calculate the total number of links on a page?

In order to count the total number of links, we needs to be capture and save the list of web elements and then calculate the size of the list, below is the example usage

List LinkList = driver.findElements(By.tagName("img"));
System.out.println("total number of images : " + LinkList.size());
for(WebElement e : LinkList) {
System.out.println(e.getAttribute("alt") + " ---> "+ e.getAttribute("src"));
}

28. Which method is used to capture screenshots in Selenium?

In Selenium we have TakesScreenshot interface to capture the screenshot.

public static String getBase64Image() {
return ((TakesScreenshot)DriverManager.getDriver()).getScreenshotAs(OutputType.BASE64);
}

29. How do take Full Page screenshots using the Ashot utility in Selenium?

In order to take Full Page screenshots using the Ashot utility in Selenium, below is the example

public static String captureFullPageScreenShot(WebDriver driver) throws WebDriverException, IOException {
String screenshotPath = System.getProperty("user.dir") + "/ScreenShots" + captureDateTime() + ".png";
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000))
.takeScreenshot(driver);
ImageIO.write(screenshot.getImage(), "png", new File(screenshotPath));
return screenshotPath;
}

30. When will we use these locators ID, Name, XPath, Or CSS Selector?

ID & Name locators will be used when there are unique identifiers & unique names available on the web application page.
CSS Selector can be used for performance only when ID & Name locators are not unique.
XPath is used only when there is no preferred locators like ID, Name, CSS Selector.

31. What is an XPath and How to create a dynamic Xpath based on text in selenium?

XPath is used to locate the elements. With the help of XPath, user could navigate through elements and attributes in an DOM to locate web elements such as textbox, button, checkbox, Image etc.

and In order to create dynamic XPath, below is the example

public static WebElement getXpathElement(String searchText) {
String MakeDynamicXpath = "//a[text()='"+searchText+"']";
return driver.findElement(By.xpath(MakeDynamicXpath));     
}

32. What is the difference between “/” and “//” ?

Single Slash “/” – Single slash represent absolute path i.e. the XPath would be created to start selection from the DOM node.

Double Slash “//” – Double slash represent relative path i.e. the XPath would be created to start selection from anywhere within the DOM.

33. What is the difference between Absolute Path and Relative Path?

Absolute XPath starts with a single forward slash(/) and It starts with top HTML node and ends with input node, as shown below in an example

/html/body/div[6]/div[3]/form/input

Relative XPath starts with a double forward slash(//). It starts from any node in between the HTML page.

//input[@id='userId']

34. How to write XPath that contains And or OR Operators ?

In Order to write XPath with AND or OR operators, below is the example usage

tagname[@title='titleName' and @class='className']
tagname[text()='value']

Conclusion

As in the end, understanding Selenium involves not only grasping theoretical concepts but also engaging with practical, scenario-based questions, which will helps you to enhance your knowledge in automation testing.

Leave a Comment