Selenium Interview Questions and Answers for 2021

HOME

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

Locator is unique address of any web element on web page. Locating elements in WebDriver is done by using the method “findElement(By.locator())”. 
Here, locator() part will be replaced with locator names, like

driver.findElement(By.id(“email”)) 
Types of Locators in Selenium

  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath – Absolute Path & Relative Path
  • CSS Selector

For more details, click here

 
2. What is an XPath?

XPath is used to locate a web element based on its XML path. 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 
Various functions used in XPath are:-
1) text()
2) contains()
3) last()
4) AND , OR
5) position()
6) following()
7) preceding()

For more details, click here

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

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. Example is given below 

driver.findElement(By.xpath("//*[@id='yDmH0d']/div/div[2]/div[2]/form/content/section/div/content/div/input")

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. Example is given below

driver.findElement(By.id("email"))

For more details, click here

4. How do we can launch the browser using WebDriver?

Firstly, we should instantiate a Chrome/Chromium session by doing the following

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
           WebDriver driver = newChromeDriver();

Set the path to the chromedriver executable

System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Automation\\Drivers\\chromedriver_win32\\chromedriver.exe");

The chromedriver is implemented as a WebDriver remote server that instructs the browser what to do by exposing Chrome’s internal automation proxy interface.

Firefox

Similarly, we can launch other browsers too like Firefox, InternetExplorer, Edge

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.Firefox.FirefoxDriver;
System.setProperty("webdriver.gecko.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\geckodriver-v0.26.0-win64\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();

MicroSoftEdge

     import org.openqa.selenium.WebDriver;
     import org.openqa.selenium.edge.EdgeDriver;
 System.setProperty("webdriver.edge.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\edgedriver_win64\\msedgedriver.exe");
          WebDriver driver = new EdgeDriver();

For more details, click here 

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

The different drivers available in WebDriver are

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

6. Explain the different exceptions in Selenium WebDriver

Exceptions in Selenium are similar to exceptions in other programming languages. The most common exceptions in Selenium are:
1. TimeoutException: This exception is thrown when a command performing an operation does not complete in the  expected time.

2. NoSuchElementException: This exception is thrown when an element with given attributes is not found on the web page. Suppose webdriver is trying to click on XPath – “//*[@id=’yDmH0d’]/div/div[2]/div[2]/form/content” which doesn’t exist on that particular web page, then below exception is displayed – org.openqa.selenium.NoSuchElementException.


3. ElementNotVisibleException: This exception is thrown when the element is present in DOM (Document Object Model), but not visible on the web page.

4. StaleElementException: This exception is thrown when the element is either deleted or no longer attached to the DOM.

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

How do you achieve synchronization in WebDriver?

There are three types of wait in Selenium WebDriver

 1.   Implicit Wait – The implicit wait will tell to the web driver to wait for certain amount of time before it throws a “NoSuchElementException“. The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception. Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script.
We need to import java.util.concurrent.TimeUnit to use ImplicitWait.

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

2.    Explicit Wait – An explicit wait is code you define to wait for a certain condition to occur before proceeding further in the code. The explicit wait will tell the web driver to wait for certain conditions like visibilityOfElementLocated and maximum amount of time before throwing NoSuchElementException exception. Unlike Implicit waits, explicit waits are applied for a particular instance only.

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Stats1_totalCount")));

3.  Fluent Wait – Fluent Wait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.

Users may configure the wait to ignore specific types of exceptions whilst waiting, such as  NoSuchElementException when searching for an element on the page.

Fluent Wait commands are mainly used when the web elements which sometimes visible in few seconds and some times take more time than usual. Mainly in Ajax applications. We could set the default pooling period based on the requirement.

Wait wait = new FluentWait(driver)  .withTimeout(Duration.ofSeconds(30))
 .pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
     return driver.findElement(By.id("foo"));
}
});

For more details, click here 

8. How to set size of Window in Selenium WebDriver?

First fetch the size of the browser window in pixels by below shown code Dimension

size = driver.manage().window().getSize();
         int width1 = size.getWidth();
         int height1 = size.getHeight();

Now, change the size of window by using

driver.manage().window().setSize(new Dimension(1024, 768)); 

9. How to set position of Window in Selenium?

First fetch the coordinates of the top left coordinate of the browser window by

Point position = driver.manage().window().getPosition();
         int x1 = position.getX();
         int y1 = position.getY();

The window can be moved to the chosen position by

// Move the window to the top left of the primary monitor
driver.manage().window().setPosition(new Point(0, 0));

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

FindElement – This method locates for the first web element on the current web page matching the criteria mentioned as parameter.  
If the web element is not found, it will throw an exception – NoSuchElementException. 

driver.findElement(By.xpath("Xpath location"));

FindElements – This method locates all the web elements on the current web page matching the criteria mentioned as parameter. 

If not found any WebElement on current page as per given element locator mechanism, it will return empty list.     

findElements (By arg0):List<WebElement

For more details, click here 

11. How to type in a textbox using Selenium?

The user can use sendKeys(“String to be entered”) to enter the string in the textbox. The sendKeys types a key sequence in DOM element even if modifier key sequence is encountered.

Syntax - sendKeys(CharSequence… keysToSend ) : void
Command – driver.findElement(By.xpath("//*[@name = 'email']")).sendKeys("abc123@gmail.com") 

For more details, click here

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

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. 

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

13. How to input text in the text box without calling the sendKeys()?

//Creating the JavascriptExecutor interface object by Type casting                                     JavascriptExecutor js = (JavascriptExecutor)driver;              
//Launching the Site        
driver.get("https://www.google.com/");                      js.executeScript("document.getElementsByName('q')[0].value = 'Selenium Introduction';");

For more details, click here

14. How to read a JavaScript variable in Selenium WebDriver? 

//To initialize the JS object
JavascriptExecutor JS = (JavascriptExecutor) webdriver;
//To get the site title
String title = (String)JS.executeScript("return document.title");
System.out.println("Title of the webpage : " + title);

For more details, click here

15. What is JavaScriptExecutor and in which cases JavaScriptExecutor will help in Selenium automation?

There are some conditions where we cannot handle some problems with WebDriver only, web controls don’t react well against selenium commands. In this kind of situations, we use Javascript. It is useful for custom synchronizations, hide or show the web elements, change values, test flash/HTML5 and so on. 
In order to do these, we can use Selenium’s JavascriptExecutor interface which executes JavaScript through Selenium driver.

It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript(Script,Arguments);

Script – This is the JavaScript that needs to execute.

Arguments – It is the arguments to the script. It’s optional
Let’s see some scenarios we could handle using this Interface:
1. To type Text in Selenium WebDriver without using sendKeys() method 2. To click a Button in Selenium WebDriver using JavaScript
3. To handle Checkbox
4. To generate Alert Pop window in selenium
5. To refresh browser window using Javascript
6. To get innertext of the entire webpage in Selenium
7. To get the Title of our webpage
8. To get the domain
9. To get the URL of a webpage
10. To perform Scroll on an application using  Selenium


For more details, click here

16. How To Highlight Element Using Selenium WebDriver?

By using JavascriptExecutor interface, we could highlight the specified element

//Create the JavascriptExecutor interface object by Type casting               JavascriptExecutor js = (JavascriptExecutor)driver; 

//Higlight element - Total PageCount
WebElement TotalCount = driver.findElement(By.id("Stats1"));js.executeScript("arguments[0].style.border='3px dotted blue'", TotalCount); 

For more details, click here

17. List some scenarios which we cannot automate using Selenium WebDriver?

1. Bitmap comparison is not possible using Selenium WebDriver.
2. Automating Captcha is not possible using Selenium WebDriver.
3. We can not read bar code using Selenium WebDriver.

18. How can you find if an element in displayed on the screen?

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.

  • isDisplsyed()
  • isSelected()
  • isEnabled()
isDisplayed():
boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();
isSelected():
boolean eleSelected= driver.findElement(By.xpath("xpath")).isSelected(); 
isEnabled():
boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();

19. Explain how you can switch back from a frame?

To switch back from a frame use method defaultContent()  

driver.switchTo().defaultContent(); 

20. What is the difference between getWindowhandles() and getwindowhandle() ?

getwindowhandles(): It is used to get the address of all the open browser and its return type is Set<String>

getwindowhandle(): It is used to get the address of the current browser where the control is and return type is string.

For more details, click here

21. How to select value in a dropdown?

To perform any operation on DropDown, we need to do 2 things:-

1) Import package org.openqa.selenium.support.ui.Select 
2) Create new Select object of class Select

Select oSelect = new Select());
Different Select Commands
  1. selectByValue
Select yselect = new Select(driver.findElement(By.id("year")));
yselect.selectByValue("1988");

2. selectByVisibleText

 Select mselect = new Select(driver.findElement(By.id("month")));
 mselect.selectByVisibleText("Apr");

3. selectByIndex

Select bselect = new Select(driver.findElement(By.name("birthday_day")));
bselect.selectByIndex(8);

For more details, click here

22. How to switch to a new window (new tab) which opens up after you click on a link?

If you click on a link in a web page and it opens a new window, but WebDriver will not know which window the Operating system consider active. To change the WebDriver’s focus/ reference to the new window we need to use the switchTo() command. driver.switchTo().window();

Here, ‘windowName’ is the name of the window you want to switch your reference to.

In case you do not know the name of the window, then you can use the driver.getWindowHandle() command to get the name of all the windows that were initiated by the WebDriver. Note that it will not return the window names of browser windows which are not initiated by your WebDriver.

Once you have the name of the window, then you can use an enhanced for loop to switch to that window. Look at the piece of code below.

String handle= driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) 
{
driver.switchTo().window(handle); 
}

//Store the ID of the original window
String originalWindow = driver.getWindowHandle();

//Check we don't have other windows open already
 assert driver.getWindowHandles().size() == 1;

 //Click the link which opens in a new window
 driver.findElement(By.linkText("new window")).click();

 //Wait for the new window or tab
 wait.until(numberOfWindowsToBe(2));
  
//Loop through until we find a new window handle
for (String windowHandle : driver.getWindowHandles()) {
    if(!originalWindow.contentEquals(windowHandle)) {
        driver.switchTo().window(windowHandle);
        break; 
    } 
}
  
//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"));  

For more details, click here

23. How to handle browser (chrome) notifications in Selenium?

In Chrome, we can use ChromeOptions as shown below.

ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver player = new ChromeDriver(options);

24. How to delete Browser Cookies with Selenium Web Driver?

driver.Manage().Cookies.DeleteAllCookies();

25. What are the different types of navigation commands?

  • driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history.
  • driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history.
  • driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements.
  • driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL.

For more details, click here

26. How can we handle Web-based Pop-ups or Alerts in Selenium?

To handle Web-based alerts or popups, we need to do switch to the alert window and call Selenium WebDriver Alert API methods.

  • dismiss(): To click on Cancel button.
  • accept(): To Click on OK button.
  • getText(): To get the text which is present on the Alert.
  • sendKeys(): To enter the text into the alert box.

For more details, click here

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

1. Using driver.navigate().refresh() command.
2. Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
3. Using driver.navigate().to(“URL”) on the current URL or driver.navigate().to(driver.getCurrentUrl());
4. Using sendKeys(Keys.F5) on any textbox on the webpage.        

28. What is Page Object Model in Selenium?

Page Object is a Design Pattern which has become popular in test automation for enhancing test maintenance and reducing code duplication. A page object is an object-oriented class that serves as an interface to a page of your AUT. The tests then use the methods of this page object class whenever they need to interact with the UI of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently all changes to support that new UI are located in one place.
The Page Object Design Pattern provides the following advantages:
There is a clean separation between test code and page specific code such as locators (or their use if you’re using a UI Map) and lay
There is a single repository for the services or operations offered by the page rather than having these services scattered throughout the tests.

For more details, click here

29. What are the different mouse actions that can be performed?

The different mouse events supported in selenium are
1. click(WebElement element)
2. doubleClick(WebElement element)
3. contextClick(WebElement element)
4. mouseDown(WebElement element)
5. mouseUp(WebElement element)
6. mouseMove(WebElement element)
7. mouseMove(WebElement element, long xOffset, long yOffset)

For more details, click here

30Write the code to double click an element in selenium?

Code to double click an element in selenium is mentioned below

Actions action = new Actions(driver);
   WebElement element=driver.findElement(By.id("elementId"));
   action.doubleClick(element).perform();

31. Write the code to right-click an element in selenium?

Code to right-click an element in selenium is mentioned below-

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

32. How to mouse hover an element in selenium?

Code to mouse hover over an element in selenium is mentioned below:-

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

33. How to do drag and drop in Selenium?

Using Action class, drag and drop can be performed in selenium.

    Actions builder = new Actions(driver);
    Action dragAndDrop = builder.clickAndHold(SourceElement).moveToElement(TargetElement).release(TargetElement).build();
    dragAndDrop.perform();

    Or
  // Create object of actions class
      Actions builder = new Actions(driver);
                       
  // Perform drag and drop operation
       builder.dragAndDrop(from, to).build().perform();

For more details,click here

34. How can we capture screenshots in selenium?

Using the getScreenshotAs method of TakesScreenshot interface, we can take the screenshots in selenium.

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));

3 thoughts on “Selenium Interview Questions and Answers for 2021

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s