Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

51.

Explain Page Object Model in Selenium?

Answer»

Page Object MODEL is an Object Repository design Pattern most commonly used in Selenium Test Automation. It is primarily used for enhancing test MAINTENANCE and reducing code duplication. Page object model (POM) can be used in any type of framework - modular, data-driven, hybrid framework or keyword driven, etc. A page object is an object-oriented class that serves as an interface to a page of the Application Under Test (AUT). The tests USE these methods of page object class whenever they NEED to interact with the UI of that page. The benefit is that if there is a UI change, there is no need to change the tests only the code WITHIN the page object needs to be changed.

52.

List the difference between driver.findElement() and driver.findElements() commands?

Answer»

The MAIN difference between driver.FINDELEMENT() and driver.FINDELEMENTS() commands is-

findElement() returns a single WebElement (which is found first) based on the locator PASSED as the parameter. Whereas findElements() returns a list of WebElements satisfying the locator VALUE passed. It returns an empty list if there are no web elements matching the locator strategy.

Syntax of findElement()-

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

Syntax of findElements()-

List <WebElement> elements = element.findElements(By.id(“value”));

Another difference between the two is- if no element is found then findElement() throws NoSuchElementException whereas findElements() returns a list of 0 elements.

53.

Explain how to upload a file using AutoIt tool?

Answer»

Download and INSTALL AutoIt tool

Open SciTE Script editor and ADD the below mentioned AutoIt script. Save it as ‘UploadFile.au3’ in your system.

Below is the AutoIt Script:

WinWaitActive("FILE Upload")  SEND("D:\SoftwareTestingMaterial\UploadFile.txt")  Send("{ENTER}")

Save it as ‘UploadFile.au3’

After the file is saved, we need to CONVERT the ‘UploadFile.au3’ to ‘UploadFile.exe’. (This can be done by Right Click on the file and click on ‘Compile Script’) .

Add the below mentioned Selenium Script and run :

Runtime.getRuntime().exec(“D:\\Automation\\AutoIt\\Uploadfile.exe”);

54.

What is a Framework?

Answer»

A Framework is nothing but a SIMPLE structure that becomes a framework when we blend various guidelines, concepts, coding standards, processes, practices, project hierarchies, modularity, REPORTING mechanism, test data injections, etc. This blend has to be in the right way and in the right techniques which MAKES it stand as a great Structure. And in layman terms we can SAY a framework is a set of rules or guidelines which should be followed while scripting to achieve the desired benefits like reduced maintenance cost, re-usability of code, increase code coverage with minimal coding.

Below are some examples of Automation frameworks:

  1. Data-Driven Testing Framework - It drives the data through the script to the application which is under test.
  2. Keyword Driven Testing Framework - It drives the data using special Keywords AVAILABLE inside the third party files (Excell, CSV, XML, Database files) to fetch and transmit the data to the application under test.
    It drives the data through the use of special Keywords to the script and then to the application under test.
  3. Hybrid Testing Framework - A framework which combines the benefits of two or more framework and designing techniques to make the testing process smooth and powerful.
  4. Behaviour Driven Framework - Test cases written in the plain English language to execute the test on the basis of the expected behaviour of the application and ease to the stakeholders (non-technical) to understand and contribute.
  5. Test-Driven Framework - An Approach in which we create a test to make it fail, then we work on the application to make it pass and then we refactor to improve the quality of the application.
55.

How to check if the button is enabled on the page?

Answer»

Using the radio button we are able to select only one OPTION from the options available and radio buttons can be toggled only by Click() method.

We should ensure the following things before performing any ACTION on the Radio buttons -

  • A radio button is displayed on the webpage
  • Radio is enabled on the webpage
  • Check the default SELECTION of the Radio button

Using a predefined isEnabled() method in SELENIUM WebDriver you can confirm whether the radio button is enabled or not.

For ex. While automating radio buttons on flight reservation site you can check -

tripRadioBtn = driver.findElement (By.locator("locator value")); tripRadioBtn.isEnabled()

This will RETURNS a Boolean value, if the output is  true then said radio button is enabled on the webpage, or output is False.

56.

How to know the element is enabled or not?

Answer»

During test case creation, you NEED to frequently verify that the targeted element is enabled or DISABLED on the web page before performing any action on it. Selenium WebDriver has built-in isEnabled() method to CHECK whether the status of the element is enabled on the web page.

If the specified element is enabled, isEnabled() method of WebDriver will verify and return true, ELSE will return false.

Syntax is  - 

driver.findElement(By.xpath(“//input[@name=’fname’]“)).isEnabled();

To take some action based on the element’s enabled status, we can use the isEnabled() method with if condition to take action.

//verify name TEXT box is enabled or not If (FirstName.isEnabled ())  { System.out.print ( “Text box First name is enabled. ”); } Else { System.out.print ( “Text box First name is disabled. ”) }
57.

How to work with Radio Buttons?

Answer»

Using the radio button we will be able to select only one OPTION from the options available and radio buttons can be toggled only by Click() method.

We should ensure the following things before PERFORMING the click event on the Radio buttons -

  • A radio button is displayed on the webpage
  • Radio is enabled on the webpage
  • Check the default selection of the Radio button

By using the Click() method in SELENIUM you can perform the action on the Radio button.

For ex.

tripRadioBtn = driver.findElement (By.id("oneway")); tripRadioBtn.click();

Selenium WebDriver has predefined METHODS -

isDisplayed() method -

WebElement tripRadioBtn = driver.findElement (By.id("id value"));

It will check tripRadioBtn.is displayed. This will returns a Boolean value, if it returns true then said radio button is present on the webpage, or it returns False.

isEnabled() method -

tripRadioBtn.isEnabled()

This will returns a Boolean value, if it returns true then said radio button is enabled on the webpage, or it returns False

isSelected() method -

tripRadioBtn.isSelected()

This will returns a Boolean value, if it returns true then said radio button is SELECTED, or it returns False

58.

Which locator you used and why?

Answer»

There are 8 types of locators in selenium WebDriver.It is very important to decide on which locator we should use.

To find web element Selenium web driver takes time which is more or less BASED on the type of locator we used. Test execution time will increase if we use a slow locator. So the selection of locator should be correct and FASTER. When we use the ID locator, Page Object Model (POM) has advantages. ID helps in identifying web element uniquely.

If a unique ID is not available, we use Name locator. Name locator may not identify a web element uniquely as a web page as multiple web elements can share the same name. We can request developers to provide a unique ID or Name for every web element to faster test script execution.

To locate a list of web elements, we use ClassName or TagName. LinkText or PartialLinkText can be used for ANCHOR tag web elements.

When web element has not Unique ID and name, CSS Selector is the best option to use. It is faster and also it improves the performance, and very compatible across browsers. CSS engine is consistent in all browsers and very useful to test applications on multiple browsers. XPath does not work in IE always so CSS is best for IE.

XPath is the last option to use as a locator as it is SLOWER among all locators, but it provides reliable ways to locate web elements. XPath engines are different in each browser and make them inconsistent across browsers.

59.

How to get cell value from the table?

Answer»

There are TWO types of HTML tables on the web that are Static table and Dynamic table.

In the Static table, DATA is static ie.rows and columns are FIXED whereas in Dynamic table rows and columns are not fixed.

Follow the steps below to get cell data –

  1. First, locate the table.
  2. Determine the total number of rows and columns
  3. From the rows and columns count locate required cells and perform ‘getText()’ method of the WebDriver ELEMENT on the element.

Syntax -

  • WebElement baseTable = driver.findElement(By.tagName("table"));
  • List  col = driver.findElements(By.xpath(“XPath"]/table/thead/tr/th"));System.out.println("No of cols are : " +col.size());
  • List  rows = driver.findElements(By.xpath("Xpath”]/table/tbody/tr/td[1]"));System.out.println("No of rows are : " + rows.size());
  • To find 3rd rowWebElement tableRow = baseTable.findElement(By.xpath("XPath"]/table/tbody/tr[3]")); STRING rowtext = tableRow.getText();
  • To get 3rd row's 2nd column dataWebElement cellIneed = tableRow.findElement(By.xpath("XPath"]/table/tbody/tr[3]/td[2]")); String valueIneed = cellIneed.getText(); System.out.println("Cell value is : " + valueIneed);
60.

How to get a number of frames on a page?

Answer»

An HTML document embedded inside the current HTML document on a web page is IFRAME. An iFrame is USED to insert content from ANOTHER source into a web page like an advertisement. A single web page can have multiple iFrames and iFrame can have an inner frame as well. The frame inside the frame is called nested frames. Content of iFrame can be changed without reloading the complete website. The IFrame is frequently used to insert content from another source into a Web page. The <iframe> tag specifies an INLINE frame.

Syntax to get number of frames on a page is -

size = driver.findElements(By.tagName("iframe")).size(); System.out.println("Total Frames --" + size); //print the number of frames on page

Here is the code to find the number of frames in a web page -

IMPORT org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class CountFrame { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("https://seleniumautomationpractice.blogspot.com/2019/07/example-of-html-iframe-alternative.html"); System.out.print("No. of Frames:"); System.out.println(driver.findElements(By.tagName("frame")).size()); System.out.print(“No. of inline Frames:”); System.out.println(d.findElements(By.tagName("iframe")).size()); } }
61.

How to switch from one frame to another frame?

Answer»

The frame is a web page embedded in another web page or an HTML document embedded in another HTML document. The IFrame is frequently used to insert content from another source into a Web page. The <iframe> tag specifies an inline frame.

The frame inside the frame is called nested frames. To switch from one frame to another first switch to the outer frame by either index or ID of the iframe. Once you switch to the outer frame you can find the total number of iframes inside the outer frame and then switch to the inner frame by any known method. You should FOLLOW the same order as we entered into the frame while exiting that is an exit from the inner frame first and then the outer frame.

Syntax to switch frame are:

DRIVER.switchTo().frame(0); (switch to outer frame) size = driver.findElements(By.tagName("iframe")).size(); (get iframe count) driver.switchTo().frame(0); (Switching to inner frame) driver.switchTo().parentFrame(); (to move back to parent frame) driver.switchTo().defaultContent(); (to move back to main frame, mostly parent frame)

Code to switch to a frame whose ID or web element is not available using index-

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class IndexOfIframe { public static void main(String[] args) {     WebDriver driver = new FirefoxDriver();     driver.get("HTTPS://seleniumautomationpractice.blogspot.com/");       driver.manage().window().maximize();     //driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);     int size = driver.findElements(By.tagName("iframe")).size();     for(int i=0; i<=size; i++){ driver.switchTo().frame(i); int total=driver.findElements(By.tagName("iframe")).size(); System.out.println(total);     driver.switchTo().defaultContent(); } } }
62.

How to know if the element will be selected or not?

Answer»

isSelected() is the method used to verify whether the desired WEB element is SELECTED or not. The best way to do this is to use the SELENIUM methods isSelected(): This method determines if an element is selected or not. isSelected() returns true if the element is selected and false if it is not. It is widely used on CHECKBOXES, radio buttons, and options in a select.

While running selenium tests, visibility conditions are necessary, because they enable you to check if an element is selected/displayed/enabled. For example, a tester may want to check if a checkbox or radio BUTTON has been selected by default before it is click. To ensure whether the checkbox or radio button is selected or not use method isSelected() as below.

Boolean isSelected() method determines whether an element is selected or not. It returns the Boolean value true if the element is selected and false if it is not. isSelected() method is predominantly used with radio buttons, dropdowns, and checkbox.

Ex. on flight booking sight you can select radio button one way or round trip

tripRadioBtn = driver.findElement (By.id("oneway")); tripRadioBtn.isSelected();

This will return a Boolean value, if it returns true then said radio button is selected, or it returns False

63.

How To Handle Multiple Popup Windows In Selenium?

Answer»

In many SCENARIOS, when you open a web site, the application displays multiple windows. Those can be advertisements or a kind of information showing on popup windows. Using Windows Handlers in selenium WebDriver, we can handle multiple.

  • STEP 1: Open website and get the main window handle by using driver.getWindowHandle();
  • Step 2: Now get all the window HANDLES by using driver.getWindowHandles();
  • Step 3: Compare all the window handles with the main Window handles and perform the operation on the window which you need.

In the below example we will see how to handle multiple windows and close all the CHILD windows which are not REQUIRED. Compare the main window handle to all the other window handles and close them.

package multialert; import java.util.Set; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.Test;  public class WindowExamples {          static WebDriver driver;          public void test_CloseWindowsExceptMainWindow() {                      driver = new FirefoxDriver();                      // Opens Naukri.com website with multiple windows                         driver.get("http://www.naukri.com/");                    // get main window handle                      String winTitle= getCurrentWindowTitle();                      String mainWindow = getMainWindowHandle(driver);                         Assert.assertTrue(closeAllOtherWindows(mainWindow));                      Assert.assertTrue(winTitle.contains("Jobs - Recruitment-Job Search"), "window title is not matching");          }                         public String getMainWindowHandle(WebDriver driver) {                      return driver.getWindowHandle();          }          public String getCurrentWindowTitle() {                      String winTitle = driver.getTitle();                      return winTitle;          }          //Except main window, close all windows.          public static boolean closeAllOtherWindows(String openWindowHandle) {                      Set<String> allWindowHandles = driver.getWinHandle();                      for (String currentWindowHandle : allWindowHandles) {                                  if (!currentWindowHandle.equals(openWindowHandle)) {                                                 driver.switchTo().window(currentWindowHandle);                                                 driver.close();                                 }                      }                         driver.switchTo().window(openWindowHandle);                      if (driver.getWindowHandles().size() == 1)                                  return true;                      else                                  return false;          } }

The below image shows you the multiple windows that open in the application. Three windows are open. One is the main window and the other two are child windows.

64.

How To Handle Window-Based Alerts/Pop-Ups In Selenium?

Answer»

Sometimes while automating, we come across scenarios where we need to handle pop-ups generated by windows like a print pop up or a browser WINDOW while uploading a file.

We know selenium is an automation testing tool that supports only web application testing. Selenium does not support windows based applications and automating window alert is not possible. Handling these pop-ups in selenium is always a bit tricky. However, along with third-party intervention, selenium can handle windows alert.

Many third-party tools are available for handling window-based pop-ups along with the selenium.

Let’s handle a window-based pop-up using the Robot class.

Robot class is a java based utility to emulate the keyboard and mouse actions.

We will automate one scenario

  1. Launch the browser and open “gmail.com”
  2. Enter username and password and click on the Sign button(Note SCRIPT has dummy username and password)
  3. Click on the compose icon
  4. Click on the attachment icon and select the file to upload with the window based pop up.

WebDriver Code using Robot Class

  • Step 1: Create a new java class named as “DemoAlertWindow” under project “Learning_Selenium”
  • Step 2: Import package import java.awt.Robot prior to the script creation.
  • Step 3: Import package java.awt.event.KeyEvent allows the USER to use keyPress and keyRelease events of a keyboard.

Below is the test script that is equivalent to the above-mentioned scenario.

  import java.awt.Robot;     import java.awt.event.KeyEvent;     import org.junit.After;     import org.junit.Before;     import org.junit.Test;     import org.openqa.selenium.By;     import org.openqa.selenium.WebDriver;     import org.openqa.selenium.firefox.FirefoxDriver;     public class DemoAlertWindow {     WebDriver driver;     @Before     public void setUp()     {     driver=new FirefoxDriver();     driver.get("https://gmail.com");     driver.manage().window().maximize();     }     @Test     public void testAlertWindow() throws Exception{     // enter a valid email address     driver.findElement(By.id("Email")).sendKeys("TestSelenium1@gmail.com");     // enter a valid password     driver.findElement(By.id("Passwd")).sendKeys("TestSelenium");     // click on the sign in button     driver.findElement(By.id("signIn")).click();     Thread.sleep(30000);     // click on compose button     driver.findElement(By.xpath("//div[@class='z0']//div[contains(text(),'COMPOSE')]")).click();     // click on attach files icon     driver.findElement(By.xpath("//div[contains(@command,'Files')]//div[contains(@class,'aaA')]")).click();     // creating instance of Robot class (A java based utility)     Robot rb =new Robot();     // pressing keys with the help of keyPress and keyRelease events     rb.keyPress(KeyEvent.VK_D);     rb.keyRelease(KeyEvent.VK_D);     Thread.sleep(2000);     rb.keyPress(KeyEvent.VK_SHIFT);     rb.keyPress(KeyEvent.VK_SEMICOLON);     rb.keyRelease(KeyEvent.VK_SEMICOLON);     rb.keyRelease(KeyEvent.VK_SHIFT);     rb.keyPress(KeyEvent.VK_BACK_SLASH);     rb.keyRelease(KeyEvent.VK_BACK_SLASH);     Thread.sleep(2000);     rb.keyPress(KeyEvent.VK_P);     rb.keyRelease(KeyEvent.VK_P);     rb.keyPress(KeyEvent.VK_I);     rb.keyRelease(KeyEvent.VK_I);     rb.keyPress(KeyEvent.VK_C);     rb.keyRelease(KeyEvent.VK_C);     Thread.sleep(2000);     rb.keyPress(KeyEvent.VK_ENTER);     rb.keyRelease(KeyEvent.VK_ENTER);     Thread.sleep(2000);     }     @After     public void tearDown()     {     driver.quit();     }     }
65.

How To Handle web-based Alerts/Pop-Ups In Selenium?

Answer»

A small message/dialogue box that appears on the top of a web application and it provides some information/warning to the USER is an alert. It may expect input information from the user.

In web applications, there are three kinds of popup boxes,

  • Alert box
  • Confirm box
  • Prompt box

Alert box-

To display some information to the user an alert box is used. The user needs to click the OK button displayed on an alert box that shows up to proceed.

Confirm box -

When an application wants to get confirmation from the user, a confirmation box is used. The user needs to click on either Yes/Ok button or No/Cancel button on the confirm box to proceed further.

Prompt box -

When an application expects input from the user immediately after opening it, a prompt box is used. After ENTERING the input, the user needs to click on either Yes/Ok button or No/Cancel button when the confirm box shows up to proceed further.

You can’t inspect any button or textbox present on any popup boxes using the Developer tool. Pop-up boxes block screen and appear on top of the screen. USERS cannot PERFORM any action on screen unless you handle these pop-ups.

User can perform below operations on these pop-ups using selenium are,

  1. Accept - to click on the OK button
  2. Dismiss - to click on Cancel button
  3. SendKeys - to enter text in the text box available on the pop-up
  4. GetText - to get label text on pop-up

Below is the code to handle alert pop-up. Please note element and test SITE is a dummy –

String alertBoxOutput, popupText;      System.setProperty("webdriver.chrome.driver", "./Resources/chromedriver.exe");  WebDriver driver = new ChromeDriver();  driver.manage().window().maximize();      driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);      driver.get("https://www.testtutorial.com");  Thread.sleep(2000);    // Alert popups      driver.findElement(By.id("alertBox")).click();  popupText = driver.switchTo().alert().getText();  Assert.assertEquals(popupText, "I am an alert box!");  driver.switchTo().alert().accept();  alertBoxOutput = driver.findElement(By.id("output")).getText();  Assert.assertEquals(alertBoxOutput, "You selected alert box");  // Confirmation popups      driver.findElement(By.id("confirmBox")).click();  popupText = driver.switchTo().alert().getText();      Assert.assertEquals(popupText, "Press a button!");  driver.switchTo().alert().accept();  alertBoxOutput = driver.findElement(By.id("output")).getText();  Assert.assertEquals(alertBoxOutput, "You pressed OK in confirm box");  driver.findElement(By.id("confirmBox")).click();  driver.switchTo().alert().dismiss();  alertBoxOutput = driver.findElement(By.id("output")).getText();  Assert.assertEquals(alertBoxOutput, "You pressed Cancel in confirm box");  // Prompt pop ups      driver.findElement(By.id("promptBox")).click();  popupText = driver.switchTo().alert().getText();  Assert.assertEquals(popupText, "Please enter your name:");      driver.switchTo().alert().sendKeys("Reddy");  driver.switchTo().alert().accept();  alertBoxOutput = driver.findElement(By.id("output")).getText();  Assert.assertEquals(alertBoxOutput, "You entered text Reddy in prompt box");      driver.findElement(By.id("promptBox")).click();  driver.switchTo().alert().dismiss();  alertBoxOutput = driver.findElement(By.id("output")).getText();  Assert.assertEquals(alertBoxOutput, "You pressed Cancel in prompt box.");     driver.quit();
66.

How to send a value into alert?

Answer»

Alerts is a popup box that takes focus away from the current browser and forces you to read the alert message. Some activities such as accepting or dismissing the alert box need to be performed to resume your task on the browser.

To handle alerts popup window, we need to call the SELENIUM WEBDRIVER Alert API method to switch to the alert window. Window-based and Web/Browser based alert are the two types of alert.

To handle Browser-based Alerts (alert popup), we use Alert Interface which provides some methods to handle the popup.

During the execution of the WebDriver script, the driver control will be on the browser. Even when after the alert generated control will be on a browser that means the driver control will be behind the alert pop up. In order to move the control to alert pop up, use the COMMAND

driver.switchTo().alert();

After SWITCHING control from browser to alert window, we can use the Alert Interface methods to perform actions such as accepting the alert, dismissing the alert, GET the text from the alert window, writing some text on the alert window, etc.,

Syntax send the value to the alert is -

alert.sendkeys(String tringToSend);
67.

How to get TagName?

Answer»

The tagName property returns the tag name of the element.

A tagName is a part of a DOM structure. Every element on a page is defined with a tag like input tag, button tag, anchor tag, etc. Each tag can have multiple ATTRIBUTES like ID, name, value class, etc. In the case of the tagName locator in Selenium, we are SIMPLY using the tag name to identify an element.

See below example of DOM structure of the login page where tag names are highlighted

- Email Field: < input type="email" name="email" value="" placeholder="Email" required="required" autofocus="autofocus" class="form-control md-5 form-control-lg"> Password Field: < input type="password" name="password" placeholder="Password" class="form-control md-5 form-control-lg" > Login Button: < button type="submit" class="btn btn-primary btn-lg btn-block md-5">LOGIN< /button > Forgot Password Link: < button type="submit" class="btn btn-primary btn-lg btn-block md-5">LOGIN< /button >

When to use this tagName locator in Selenium? where you do not have attribute values like ID, class, or name and you want to locate an element, you can use the tagName locator in Selenium. For example, to retrieve data from a table, you can use < td > tag or < tr > tag.

Similarly, in a scenario where you wish to verify the number of links on a page and verify whether links are WORKING or not, you can locate all such links through the anchor tag.

The COMMAND to identify an element via tagName is:

driver.findElement(By.tagName("input"));

This method is not reliable while locating individual elements and the page might have multiple INSTANCES of these elements.

68.

How to get attributes?

Answer»

In automation, there are cases where you want to get the values of the attribute and then perform any action

The attribute value will be NULL for the TAG that does not exist.

To add extra meaning to a web element, a web developer defines the attribute. Attributes have additional information about an HTML element and come in name="value" pairs. Attributes are defined by HTML. We retrieve the values of attributes of web elements to verify test cases. LET us consider a movie ticket booking application. Where available seat colour will be green and booked seat colour will be red, so, to check whether a seat is available or already booked, we need to FETCH attribute (colour) value through the script and based on the value we need to perform operations. To achieve this Selenium WebDriver provides a method called getAttribute() which is declared in WebElement interface. It returns the value of the web element a String of the Web element. getAttribute() method returns either “true” or null for attributes whose value is Boolean. getAttribute() method work on specific web elements, so first you need to locate a web element and then call getAttribute() method on it by specifying the attribute for which value you require.

To get the attribute value using selenium WebDriver, we can use

'element.getAttribute(attributeName)'. WebElement searchTextBox= driver.findElement(By.id("lst-ib")); // retrieving html attribute value using getAttribute() method String titleValue=searchTextBox.getAttribute("title");
69.

How to create Web elements in selenium?

Answer»

WebElement is HTML DOM(document object model) element. When a browser loads HTML document, WebElement CONVERTS into the document object. WebElement is a class in selenium WebDriver and converts an object into the document object. Text Box, text, button, link table, radio button, checkbox, ETC, present on the webpage is webelement. Selenium needs to identify these elements uniquely before performing any action on webelement. WebElement commands will apply to almost all DOM elements on the page and used to interact with visible as well as invisible elements present on-page.

Below are some important WebElement Methods -

1. Clear(): Clear() command will clear the value in the text box if the element is text entry element. No parameters required for this method.

//Create WebElement WebElement clearElement = driver.findElement(By.id("id value")); // Clear text clearElement.clear(); // Or driver.findElement(By.id("id value")).clear()

2. SendKeys: This mimics typing and sets the value into an element. Character sequence is the parameter required for this method and returns nothing. This method used for text entry elements like INPUT and Text Area elements.

//Create WebElement WebElement sendkeyElement = driver.findElement(By.id("id value")); // Send text sendkeyElement.sendKeys("Sample Text"); //OR driver.findElement(By.id("id value").sendKeys("Sample Text"));

3. Click():  To click any element on a web page, Click() command is used and is the most COMMON way of interacting with web elements like link, radio buttons, checkboxes, etc. No parameters required for this method.

//Create WebElement WebElement clickElement = driver.findElement(By.id("id value")); //Click on an element clickElement.click(); //OR driver.findElement(By.id("id value")).click();

4. isDisplayed(): To check if an element is currently displayed or not? isDisplayed() command is used. No parameter is required with this command and returns a boolean value. If an element is present on the page, it will return true else throws 'NoSuchElementFound exception' exception.

//Create WebElement WebElement  displayElement = driver.findElement(Bt.id("id value")); //perform operation displayElement.isDisplayed(); //Or driver.findElement(By.id("id value")).isDisplayed();

5. isEnabled():  To check if an element is currently enabled or not? isEnabled() command is used. No parameter is required with this command and returns a boolean value. If an element is enabled on the page, it will return true.

//Create WebElement WebElement enabledElement = driver.findElement(By.id("id value")); //perform operation e.g. on radio button or checkbox enabledElement.isEnabled(); //Or driver.findElement(By.id("id value")).isEnabled();

6. isSelected(): To determine whether the element is selected or not, isSelected() method is used. No parameter is required with this command and returns a boolean value. If an element is currently selected or checked, it will return true. This method applies to input elements like Checkboxes, radio buttons, etc.

//Create WebElement WebElement selectedElement = driver.findElement(By.id("id value")); selectedElement.isSelected(); //Or driver.findElement(By.id("id value")).isSelected();

7. Submit(): If an element is a form or an element within a form, Submit() method works well. No parameter is required with this command and returns nothing. As an impact of Submit(), current web page changes, Submit() method will wait till new page loads.

//Create WebElement WebElement submitElement = driver.findElement(By.id("id value")); //Perform submit submitElement.Submit(); //Or driver.findElement(By.id("id text").Submit();

8. getText(): getText() method fetch visible inner text of the element. No parameter is required to pass but returns string value.

//Create WebElement WebElement gettextElement = driver.findElement(By.id("id text")); //perform getText operation gettextElement.getText(); //Or driver.findElement(By.id("id value")).getText();

9. getTagName(): This method returns the tag name of the web element. No parameter is required to pass.

//Create WebElement WebElement tagnameElement = driver.findElement(By.id("id value")); //perform operation tagnameElement.getTagName(); //Or driver.findElement(By.id("id value")).getTagName();

10. getAttribute(): This method returns the value of the given attribute of the element. A string is accepted as a parameter and returns String value.

//Create WebElement WebElement attributeElement = driver.findElement(By.id("id value")); //perform operation attributeElement.getAttribute("Attribute"); //Or driver.findElement(By.id("id value")).getAttribute("Attribute");

11. getCssValue(): This method returns CSS property value of the given element. No parameter is required to pass and return a string value.

//create webelement WebElement cssElement = driver.findElement(By.cssSelector("css value")); cssElement.getCssValue();

12. getSize(): This method returns the width and HEIGHT of the element. No parameter is required to pass and return the size of the element on the page.

//Create WebElement WebElement sizeElement = driver.findElement(By.id("id value")); Dimension dimensions = element.getSize(); System.out.println("Height :" + dimensions.height + "Width : "+ dimensions.width);

13. getLocation(): To locate location of the element getLocation() method is used. No parameter is required to pass but returns the Point object, from which we get X and Y coordinates.

//create WebElement WebElement LocationElement = driver.findElement(By.id("Btn")); Point pnt = element.getLocation(); System.out.println("X coordinate : " + point.x + "Y coordinate: " + point.y);

Let us see, the EXAMPLE of creating WebElement on facebook.com -

import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class WebElement_Create { public static void main(String[] args) throws InterruptedException { WebDriver driver = new FirefoxDriver(); // Wait to load page   driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); // Set driver path System.setProperty("webdriver.gecko.driver", "C:\\geckodriver.exe"); // Redirect to url driver.get("https://facebook.com"); //============ clear() ==================== // Create WebElement WebElement clElement = driver.findElement(By.id("email")); // Perform clear operation clElement.clear(); // ========== sendKeys() ================= // Create WebElement WebElement keyElement = driver.findElement(By.id("email")); // Perform sendKeys operation keyElement.sendKeys("Anderson@gmail.com"); //============ click()===================== // Create WebElement WebElement clickElement = driver.findElement(By.id("u_0_2")); // Perform click operation clickElement.click(); //============ isDisplayed() ============= // Create WebElement WebElement displayElement = driver.findElement(By.id("u_0_2")); // Perform isDisplayed operation String disp = displayElement.isDisplayed(); System.out.println(disp); //========== isEnabled() =============== // Create WebElement WebElement enabledElement = driver.findElement(By.id("u_0_2")); // Perform isEnabled operation String ena = enabledElement.isEnabled();  System.out.println(ena); //=========== isSelected() =========== // Create WebElement WebElement selectedElement = driver.findElement(By.id("u_0_2")); // Perform eleSelected operation String tSelect = eleSelected.isSelected(); System.out.println(tSelect ); // ============ submit() ========== // Create WebElement WebElement submitElement = driver.findElement(By.id("u_0_15")); // Perform submit operation submitElement .submit(); // =========== getText() =============== // Create WebElement WebElement textElement = driver.findElement(By.id("u_0_2")); // Perform getText operation textElement.getText(); //=========== getTagName() ============== // Create WebElement WebElement tagnameElement = driver.findElement(By.id("u_0_2")); // Perform getTagName operation String tName = tagnameElement.getTagName(); System.out.println(tName); //========== getAttribute() =============== // Create WebElement WebElement attributeElement = driver.findElement(By.id("u_0_2")); // Perform getgetAttribute operation String attri = attributeElement.getAttribute("Attribute"); System.out.println(attri); // ============ cssSelector() ================= // Locating textBox element using CSS Selector WebElement signButton = driver.findElement(By.cssSelector("#u_0_15 ")); System.out.println(signButton); // =============== getSize() =================== WebElement dimensionsElement = driver.findElement(By.id("u_0_15")); Dimension dimensions = dimensionsElement.getSize(); System.out.println("Height :" + dimensions.height + "Width : " + dimensions.width); // ======= getLocation() ======================== WebElement locationElement = driver.findElement(By.id("u_0_15")); Point point = locationElement.getLocation(); System.out.println("X coordinate : " + point.x + "Y coordinate: " + point.y);         } }
70.

What are the different types of frameworks?

Answer»

There are different frameworks available in selenium, but below THREE frameworks are POPULAR and you can CREATE these three different TYPES of frameworks using selenium are -

Data-Driven Framework:- Currently Data Driven Framework is one of the popular automation testing frameworks. 

The entire test data is generated from some external files like Excel, CSV, XML or some database table,  and it is called Data Driven framework. The data-driven test performs the same functionality with multiple input values.

Keyword Driven Framework:- Keyword driven framework is also known as Table driven testing or action word based testing.

When the INSTRUCTIONS and operations are written in a different external file like an Excel worksheet, it is called Keyword Driven framework. It is used to speed up automation testing by using the keywords for a common set of actions.

Hybrid Framework:- It is a combination of both the Data-Driven framework and the Keyword Driven framework is called the Hybrid framework. Keywords are written in external files like excel file and code will call this file and execute test cases.

71.

How to handle a dropdown in Selenium WebDriver? How to select a value from the dropdown?

Answer»

Questions on the dropdown and selecting a value from the dropdown are common Selenium interview questions.

You should know that to work with a dropdown in Selenium, always make use of HTML tag: ‘select’. Without using ‘select’, you cannot handle dropdowns. 

So the STEPS to select an element from the drop-down are -

  1. Identify the ‘select’ HTML tag as dropdowns must have the ‘select’ tag)
  2. Select an option from that dropdown element

To identify the ‘select’ html element from the web page, use findElement() method. Look at the below piece of code:

  • WebElement mySelectElement = driver.findElement(By.id("id value"));
  • Select dropdown = new Select(mySelectElement);

Now to select an option from that dropdown can be done in THREE WAYS:

  • dropdown.selectByVisibleText(“text1”); → Select an option by the visible text.
  • dropdown.selectByIndex(“1”); → Select, by choosing the INDEX number of a option.
  • dropdown.selectByValue(“value”); → Select by choosing the value.

These are the different ways to select a value from a dropdown.

72.

What is Page Factory?

Answer»

Page Factory class in selenium is an extension of the Page object design pattern. 

Page Factory is an inbuilt concept that provides an optimized way to implement the Page Object Model. Here optimization is, it refers to the fact that the memory utilization is very good and ALSO the implementation is done in an object-oriented manner.

It is used to initialize the elements on the Page Object or instantiate the Page Objects. Annotations for elements can be created and recommended as the describing properties may not always be descriptive enough to differentiate one object with the other.

Here the concept of separating the Page Object Repository and Test Methods is followed. Instead of using ‘FindElements’, here we use annotations like @FindBy to find WebElement, and the initElements method to initialize web elements from the Page Factory class. It makes handling "Page Objects" easier and optimized by providing the  @FindBy ANNOTATION and initElements method.

@FindBy annotation - can accept attributes tagName, partialLinkText, name, linkText, id, CSS, className &AMP; XPath and is used to locate and declare web elements using different locators.

Example - @FindBy(id="elementId") WebElement element;

initElements() - is a static method of PageFactory class used in conjunction with @FindBy annotation. Web elements located by @FindBy annotation can be initialized using the initElements method. 

Example - initElements(WebDriver driver, java.lang.Class pageObjectClass)

73.

What is the difference between setSpeed() and sleep() methods?

Answer»

Both setSpeed() and sleep() will delay the speed of script execution.

THREAD.sleep(): It will stop the current execution of script thread for a specified period of time. It is done only once and it takes a single ARGUMENT in integer format

For example: thread.sleep(2000)- Execution of the script will be stopped for 2 seconds

It waits only once at the command given at sleep.

SetSpeed(): It will stop the execution of each and every selenium command for a specific amount of time and it takes a single argument in integer format

For example selenium.setSpeed(“2000”)- It will wait for 2 seconds for each and every command before the execution of the next command.

It runs each command after setSpeed delay by the number of milliseconds mentioned in set Speed.

74.

What are the different mouse actions that can be performed?

Answer»

Selenium has the ability to handle various types of keyboard and MOUSE events. In order to perform action events, use org.openqa.selenium.interactions Actions in CLASS. This API includes actions such as clicking multiple elements, drag and drop.

Let us create an object action of Action class.

  • Actions action = new Actions(driver);

Now to focus on an element using WebDriver use action -

  • actions.moveToElement(element).perform();

Here perform() method is used to execute the action.

Let us see mouse events using selenium action class API -

  • click() : It Clicks on an element.
  • doubleClick() : Double clicks onElement.
  • contextClick() : Performs a context-click on an element. 
  • clickAndHold() : It Clicks on an element without releasing.
  • dragAndDrop(source, target) : Invokes click-and-hold at the LOCATION and moves to the target location of the element before releasing the mouse. where the source is an element to grab and the target is the element to release. 
  • dragAndDropBy(source, XOFFSET, yOffset) : Performs click-and-hold at the source location and shifts by a GIVEN offset, then frees the mouse. Here xOffset is to shift horizontally and yOffset is to shift vertically.
  • moveByOffset(x-offset, y-offset) : Shifts the mouse from its current position (or 0,0) by the given offset. 
  • moveToElement(toElement) : Shifts the mouse to the centre of the element. 
  • release() : Releases left mouse button at the existing mouse location
75.

How to handle Ajax calls in Selenium WebDriver?

Answer»

Using Selenium WebDriver, HANDLING of AJAX calls is one of the common issues. Users will not be aware when the AJAX CALL would be completed and the page has been updated. 

AJAX stands for Asynchronous JavaScript and XML and AJAX ALLOWS the web page to retrieve small amounts of data from the server without reloading the entire page. From the client to server AJAX sends HTTP requests and then process the server’s response without reloading the entire page. Wait commands may not work to handle AJAX control in such a scenario and it is just because the actual page is not going to refresh.

For example, When you click on the submit button, the required information may APPEAR on the web page without refreshing the browser or sometimes it may load in a second or sometimes it may take longer. And you do not have any control overloading time. The best way to handle this kind of situation in selenium is to use dynamic waits that are WebDriverWait in combination with ExpectedCondition.

Some of the methods available are as follows:

  1. titleIs() – titleIs() waits for a page to load with a specific title. wait.until(ExpectedConditions.titleIs(“Google”));
  2. elementToBeClickable() – elementToBeClickable() waits for an element to be clickable i.e. element should be present/displayed/visible on the screen as well as enabled.
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath")));
  3. alertIsPresent() – alertIsPresent () waits for an alert box to appear.
    wait.until(ExpectedConditions.alertIsPresent()) !=null);
  4. textToBePresentInElement() – textToBePresentInElement() waits for an element having a certain string pattern.
    wait.until(ExpectedConditions.textToBePresentInElement(By.id(“title’”), “text to be found”));
76.

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

Answer»

In selenium mostly we click on an element using click() METHOD.

Many times web controls don’t react against selenium commands and we face issues with the Click() statement. To overcome such a situation, in selenium we use the JavaScriptExecutor interface.

JavaScriptExecutor executes Javascript using Selenium driver and provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

To execute JavaScript within the browser using the Selenium WebDriver script, writing a separate script is not required. Just use a predefined interface NAMED ‘Java Script Executor’ and need to import the JavascriptExecutor package in the script.

Package:

import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.JavascriptExecutor;

Syntax:

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

where Script is the JavaScript to be executed.

Arguments are the arguments to the script and are optional and can be empty.

JavascriptExecutor returns either Boolean, or LONG, or String, or List, or WebElement, or null.

Let us discuss some scenarios we could handle using JavascriptExecutor :

  1. Without using the sendKeys() method, you can use this interface to type Text in Selenium WebDriver.
  2. Using JavascriptExecutor, you can click on a Button.
  3. You can use it to handle the Checkboxes.
  4. It can be used to generate the Alert Pop window.
  5. You can Refresh browser window using Javascript
  6. You can get the inner text of the entire webpage in Selenium
  7. Get the TITLE of webpage
  8. Get the domain
  9. Get the URL of a webpage
  10. Perform Scroll on an application using Selenium
  11. Click on a SubMenu which is only visible on MOUSE hover on Menu
  12. Navigate to a different page using Javascript.
77.

How to achieve Database testing in Selenium?

Answer»

We know Selenium WebDriver is a tool to automate User Interface and We could only INTERACT with Browser using Selenium WebDriver.

We may face a situation where we want to get the data from the database or to update or delete the data from the Database.  If we want to automate anything outside the browser, we need to use other tools to achieve the task. For Database connection and work on it, use JDBC  API Driver. 

JDBC API lets the user connect and interact with the Database and fetch the data based on the queries used in the automation SCRIPT. JDBC is a SQL LEVEL API that allows EXECUTING SQL statements. It creates connectivity between Java Programming Language and the database.

To make a connection to the database the syntax is -

DriverManager.getConnection(URL, "userid", "password" )

where the user ID is the username in the database

Password of the configured user

URL format is 'jdbc:< dbtype>://ipaddress:portnumber/db_name'

<dbtype> is the driver for the database to be connected. 

Code to create a connection is -

Connection con = DriverManager.getConnection(dbUrl,username,password);

Code to load JDBC Driver -

Class.forName("com.mysql.jdbc.Driver");

Once connection is set, use Statement Object to send queries -

Statement stmt = con.createStatement();

Once the statement object is created use executeQuery method

stmt.executeQuery(SELECT *  from employee;);
78.

Explain Headless browser testing. Advantages and disadvantages of Headless testing.

Answer»

A headless browser is a browser that does not have a GUI. It is used to simulate programs even though there is no browser installed on the local system. You will not see the browser in your system but will get the RESULT in the CONSOLE. The headless browser does not have GUI means program runs in the background without GUI.

Two headless browsers widely used are HtmlUnitDriver and PhantomJSDriver.

Advantages of performing Headless browser testing -

  1. It is faster. Compared to browser automation, performance is better. Running regression scripts using browser takes lots of time, but with headless browsers, time is saved.
  2. It allows you to run scripts on a system that does not have a browser.
  3. It helps in EXECUTING scripts on different browser versions on the local system even though that browser VERSION is not AVAILABLE on the system. Most of the headless browsers support browser versions.

Disadvantages of Headless browsers testing -

  1. Debugging is difficult using headless browsers as the browser is not available. The only way is to capture a screenshot.
79.

How To Read Data From Excel File?

Answer»

To read and write an excel FILE, the Apache POI library is capable to read and write both xls and xlsx file format of excel.

Below are the steps to write to excel sheet -

  1. Create an xlsx file and save it at the desired location( d:/test/testdata.xlsx). Add some DATA to read by selenium and rename sheet (ex. mysheet). 
  2. By default excel cell format is general, make it text.
  3. Close that excel file before the execution of the script.
  4. You NEED to download POI jars and unzip it. POI jars allow to create, modify, and display MS Office files using Java programs. Go to the official website of Apache POI download section http://poi.apache.org/download.html
  5. In your editor Select Project
  6. Right-CLICK on the project
  7. Go to build path
  8. Go to 'Configure build path;
  9. Click on the 'lib' tab and, 
  10. add POI external jar files.
  11. Below is the code to read excel file
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.testng.annotations.Test;  public class ReadExcel {  public static void main(String []args){   try {   // To specify the path of file   File src=new File("filepath/excelsheetname.xlsx");    // To load file    FileInputStream fis = new FileInputStream(src);    // To load workbook    XSSFWorkbook wb=new XSSFWorkbook(fis);    // To load sheet- Here loading the first sheet       XSSFSheet sh1= wb.getSheetAt(0);   // getRow() to specify which row we want to read.   // and getCell() to specify which column to read.   // getStringCellValue() to specify that we are reading String data.  System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());  System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());  System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());  System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());  System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());  System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());   } catch (Exception E) {    System.out.println(e.getMessage());   }   }  }
80.

How To Write Data In Excel File

Answer»

To read and write an excel file, the Apache POI LIBRARY is capable to read write both xls and XLSX file format of excel.

Below are the steps to write to excel sheet -

  1. Create an xlsx file and save it at the desired location( d:testdata.xlsx). Add some data to read by selenium and rename sheet (ex. mysheet). 
  2. By default excel cell format is general, make it text.
  3. Close that excel file before the execution of the script.
  4. You need to download POI jars and unzip it. POI jars allow to create, modify, and display MS Office files using Java programs. Go to the official website of Apache POI download section http://poi.apache.org/download.html 
  5. In your editor Select Project
  6. Right-click on the project
  7. Go to build path
  8. Go to 'Configure build path;
  9. Click on the 'lib' tab and, 
  10. add POI external JAR files.
  11. Below is the code to write excel file
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.testng.annotations.Test; public class WriteExcel {  public STATIC void main(String []args){   try {   // To specify the file path which you want to create or write   File src=new File("./test/testdata.xlsx");   // To LOAD the file   FileInputStream fis=new FileInputStream(src);    // To load the workbook    XSSFWorkbook wb=new XSSFWorkbook(fis);   // To get the sheet to modify or create    XSSFSheet sh1= wb.getSheetAt(0);  // here createCell will create column and setCellvalue will set the value  sh1.getRow(0).createCell(2).setCellValue("2.31.0");  sh1.getRow(1).createCell(2).setCellValue("3.5");  sh1.getRow(2).createCell(2).setCellValue("4.66"); // to specify where you want to save file  FileOutputStream fout=new FileOutputStream(new File("location of file/filename.xlsx")); // finally write content   wb.write(fout); // close the file  fout.close();   } catch (Exception e) {    System.out.println(e.getMessage());   }   }  }
81.

What are the advantages of POM?

Answer»

Using POM an Object Repository can be created and can be maintained in the separate file.

  • Code reusability – You can achieve code reusability by writing the code once and use it in different tests.
  • Code maintainability – There is a CLEAN separation between test code and PAGE specific code such as locators and layout which makes it very easy to maintain code. Code changes happen only on Page Object Classes when a UI change occurs and enhances test maintenance and reduces code duplication.
  • Object Repository – Each page is defined as a java class and all the fields on the page will be defined in an interface as members, and the class will then implement the interface.
  • Readability – Due to a CLEAR separation between test code and page-specific code, there is an ENHANCEMENT in readability.
82.

What is Page Object Model or POM?

Answer»

POM that is Page Object Model is a design pattern popular in selenium to create object repository for web UI elements. It is a widely used design pattern for enhancing test maintenance and to avoid code duplication. It can be used in a type of framework such as MODULAR, data-driven, keyword-driven, ETC. POM is an object-oriented class works as an interface to the page for application under test. Under the page object model, for each web page in the application, there must be a corresponding page class. Web element of that web page will be identified by page class and this page class also contains Page methods which perform operations on those WebElements. As per the TASK performed by these methods, the name of these methods is given.

POM allows Operations. POM concept makes the test scripts cleaner and EASY to understand. With the help of POM, the object repository is created independent of test cases, so you can use the same object repository for a different purpose with different tools. We can integrate POM with TestNG/JUnit for functional testing and as well as with JBehave/Cucumber for ACCEPTANCE testing.

83.

What are some commonly encountered exceptions in selenium?

Answer»

Some of the COMMONLY seen exceptions in selenium are-

  1. NoSuchElementException -  You get this exception when the locator mentioned in the Selenium Program code is unable to find the web element on the web page.
  2. ElementNotVisibleException - You get this exception when a WebDriver is ABLE to locate web elements on the current webpage but it is not visible on the screen.
  3. NoAlertPresentException - You get this exception when we try to switch to an alert but the TARGETED alert is not present.
  4. InvalidElementStateException - You get this exception when the state of an element is not appropriate for the desired action.
  5. NoSuchAttributeException - You get this exception when you are trying to fetch an attribute's value but the attribute is not correct.
  6. WebDriverException - You get this exception when there is an issue with driver instance preventing it from GETTING launched.
  7. NoSuchFrameException - You get this exception when you try to switch to a frame but the targeted frame is not present.
  8. NoSuchWindowException - You get this exception when you try to switch to a window but the targeted window is not present.
  9. UnexpectedAlertPresentException - You get this exception when an unexpected alert blocks the normal interaction of the driver.
  10. TimeoutException - You get this exception when a COMMAND execution gets a timeout.
84.

What are some expected conditions that can be used in Explicit waits?

Answer»

Some of the commonly used expected conditions of an element that can be used with explicit waits are-

  • elementToBeClickable(WebElement element or By locator) - An expectation for checking an element is visible or not and enabled so that you can click on it.
  • stalenessOf(WebElement element) - will Wait until an element is no longer ATTACHED to the DOM or TIMEOUT expires.
  • visibilityOf(WebElement element) - visibilityOf(WebElement element) is used for checking that an element is present on the DOM of a page and visible.
  • visibilityOfElementLocated(By locator) - Used to check if the element is present on the DOM of a page and it is visible.
  • invisibilityOfElementLocated(By locator) - invisibilityOfElementLocated(By locator) used for checking an element is invisible or not present in the DOM.
  • attributeContains(WebElement element, String attribute, String VALUE)  - Waits for a certain text fragment to appear in the attribute.
  • alertIsPresent() - alertIsPresent(), accepts any present alert. and returns TRUE if there is an alert to click
  • titleContains(String TITLE) -  titleContains(String title) used for checking that the title of a page contains a case-sensitive substring.
  • titleIs(String title) - wait till the title of the page is the same as mentioned in the attribute. 
  • textToBePresentInElementLocated(By, String) - wait till expected text appears on targeted element.
85.

What is the use of the driver.get("URL") and driver.navigate().to("URL") commands? Are there any differences between the two?

Answer»

driver.get("URL") and driver.navigate().to("URL")  both these commands are used to navigate to a URL passed as parameter.

There is a very little difference between the two commands-

driver.navigate() command maintains browser history or cookies to navigate back and forward and ALLOWS you moving back and forward in browser history USING driver.navigate().forward() and driver.navigate().back() commands. driver.navigate() command used to navigate to the particular URL and it does not wait to page load.

In the CASE of a single page application, where the URL is appended by '#' to navigate to a DIFFERENT section of the page, driver.navigate().to() navigates to a particular page by changing the URL without refreshing the page whereas the driver.get() refreshes the page also and waits for the page to load. This refreshing of the page is also the primary reason because of which history is not maintained in the case of the driver.get() command.

86.

What do you mean by a Relative path?

Answer»

Relative XPath is a URL that contains a portion of the full path and it is alternatively referred to as a partial path or non-absolute path. A relative path is used to specify the location of a DIRECTORY relative to another directory. A relative path starting from the element you want to refer to and GO from there. Relative XPaths are preferred as they are not complete path and chances of changes are less compared to an absolute path. Its complete location is based on its relation to the directory to which it is linked.

Relative XPath starts with Double forward slash(//). For example, for google login PAGE //*[@title=’google’]

  • It directly interacts with the current node of the element.
  • It is the shortest way to navigate to an element on a webpage.
  • With the use of relative Xpath, you can handle DYNAMIC elements too.
  • In Relative XPath, we have various functions with which we can create a more ROBUST and customized Xpath for better element handling.
87.

What do you mean by Absolute path?

Answer»

ABSOLUTE XPath is a direct way to finding an element and it starts with the root node or a SINGLE forward-slash (/). It is similar to what we do in our system when a particular file path is to be SPECIFIED [eg: D:\photos\new album\myimage.JPG ] and in that case if you move the file to another location [eg: D:\photos\old album\myimage.JPG ] it will not be found correctly by the path, the same applies to the Absolute Xpath concept too, so for any changes made in the application hierarchy which have an impact on that particular element then the XPath of the element will definitely fail. Hence, absolute Xpath is not considered to be a reliable technique to LOCATE an element. 

  • SYNTAX: //html/body/tag1[index]/tag2[index]/.../tagN[index]
  • Example: //html/body/div[2]/div/div[2]/div/div/div/fieldset/form/div[1]/input[1]
88.

What are the types of XPATH?

Answer»

XPATH stands for XMLPath. Using XPath you can navigate to any element in an XML document. As  XML is a component of HTML, XPath can be used to find web elements on any web PAGE. Relative XPath and absolute XPath are two types of XPath.

  • Absolute XPath: Absolute XPath is the direct way to find the element. The disadvantage of the absolute XPath is that for any changes made in the path of the element then that XPath will fail. 
  • Relative XPath: Relative XPath is a URL that CONTAINS a portion of the full path and it is alternatively referred to as a partial path or non-absolute path. A relative path is used to specify the LOCATION of a directory relative to another directory. A relative path starting from the element you want to refer to and GO from there.
89.

How will you retrieve certain properties from CSS to Selenium?

Answer»

To find the web element on the page, the CSS locator can be used.

Syntax is - div[ID="id value"] &GT; button[value="value text"];

selects the button with its value property set at value text if children of the id value are div

PROS:

  • Faster than XPath
  • good balance between STRUCTURE and attributes
  • Allows selection of elements by their surrounding context

CONS:

  • More complex and require a steeper learning curve

Structure-Dependent Or Not?

Locators are classified into two categories ie Structure-based locators and Attributes-based locators.

  • Locators that depends on the structure of the page to find elements are structured based locator. Below locators are structure-based locators.
    •  XPath
    • DOM
    • CSS
  •  Locators that depend on the attributes of the elements to LOCATE are Attribute-based locators. Below locators are the Attribute-based locators.
    • Identifier
    • Id
    • Name
    • Link
    • CSS
  • Consider all these points pertaining to CSS before choosing a locator strategy
  • CSS is used widely because it is flexible and GIVES a good balance between using structure and attributes to find the elements.
90.

What does Locator mean? Name different types of locators.

Answer»

Id Locator :

The ID locator SEARCHES for an element having an id attribute corresponding to the specified pattern on the page.

Syntax is - driver.findElement(By.id("id value"));

PROS:

  • Each id is expected to be unique, so no chance of matching several elements

CONS:

  • Works on elements with fixed ids and not generated ones

Name Locator :

The Name locator searches for an element having a name attribute corresponding to the specified pattern on the page. You can specify a filter to refine your locator.

Syntax is - driver.findElement(By.name("name-value"));

PROS:

  • Fits well with a fixed list of similar elements

CONS:

  • It is difficult to use with data-bound lists

Link Locator:

The link locator is intended to select links only and selects the anchor element containing the specified text: link=The text of the link

Syntax is - driver.findElement(By.linkText("link text"));

PROS:

  • Selects only anchor elements
  • Useful in testing navigation

CONS:

  • You should know the text of the link in advance

DOM Locator :

The DOM locator works by locating elements that match the javascript expression referring to an element in the DOM.

Locating by getElementById

Syntax is - document.getElementById("id of the element");

Locating by getElementsByName

Syntax is - document.getElementsByName("name")[index];

Locating by DOM - dom: name

Syntax is - document.forms["name of the form"].elements["name of the element"]

  • name of the form = the value of the name attribute of the element you want to access of the form tag
  • name of the element = the value of the name attribute of the element you want to access

Locating by DOM - dom: index

Syntax is - document.forms[index of the form].elements[index of the element]

  • index of the form = With respect to the whole page, the index number (starts at 0) of the form
  • index of the element = With respect to the whole form, the index number (starts at 0) of the element

PROS:

  • Javascript allows building dynamic locators

CONS:

  • Depends on the structure of the page

XPath Locator:

XPath is the navigation tool for XML. XPath can be USED everywhere where there is XML. Xpath Locate element by using an XPath expression.

Syntax is -  

//button[@value="value text"];  //div[@id="id value"]/button[0];

PROS:

  • Very precise locators

CONS:

  • Slower compared to CSS
  • Depends on the browser’s XPath implementation which is not always complete and not recommended for cross-browser testing

CSS Locator

To find the elements on the page, the CSS locator uses CSS selectors.

Syntax is - div[id="id value"] > button[value="value text"];

selects the button with its value property set at value text if children of the id value are div

PROS:

  • Faster than XPath
  • good balance between structure and attributes
  • Allows selection of elements by their SURROUNDING context

CONS:

  • More complex and require a steeper learning curve

Structure-Dependent Or Not?

Locators are classified into two categories ie Structure-based locators and Attributes-based locators.

  • Locators that depends on the structure of the page to find elements are structured based locator. Below locators are structure-based locators.
    • XPath
    • DOM
    • CSS
  • Locators that depend on the attributes of the elements to locate are Attribute-based locators. Below locators are the Attribute-based locators.
    • Identifier
    • Id
    • Name
    • Link
    • CSS
  • Consider all these points pertaining to CSS before CHOOSING a locator strategy
  • CSS is used widely because it is flexible and gives a good balance between using structure and attributes to find the elements.
91.

How do you achieve synchronization in WebDriver?

Answer»

When two or more components work together to perform any action, we expect these components to work together at the same pace, and the coordination between these components to run parallel is called Synchronization. We require synchronization so that the Application Under Test(AUT) and testing TOOL are running in sync with each other.

Most of the web applications are developed using JavaScript and Ajax and it might happen that some of the elements may load at distant time intervals, because of which we may see “ElementNotVisibleException” or “'NoSuchElementException” exceptions. To handle these scenarios, we use Synchronization/wait to overcome these exceptions.

Two components are involved in Automation Testing is Application under test and Test Automation Tool.

While writing scripts we must ensure these two components move with the same desired pace, because both have their own agility and therefore, avoid Errors which will exhaust time in debugging.

There are two types of Conditional Synchronization:

  1. Implicit Wait
  2. Explicit Wait

Implicit Wait

Implicit Wait tells the WebDriver before throwing exception NoSuchElement/ElementNotVisible, to wait until the stated time. Waiting time between each consecutive step is taken by DEFAULT across the test script. So, the next test Step will be executed only when the SPECIFIED time is elapsed.

Syntax:

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));

The Implicit wait takes two arguments: TimeSpan (timeToWait) and time measure.

  • FromMilliSeconds
  • FromSeconds
  • FromMinutes
  • FromHours
  • FromDays

Explicit Wait:

When page load dynamically explicit WAITS are good to use. Before throwing NoSuchElement (or) ElementNotVisible Exceptions, explicit Wait tells the WebDriver to Wait till the specified condition is met or maximum time elapses. Explicit waits are APPLIED for the specified test Step in the test script.

We must first create an instance for the “WebDriverWait” class to use Explicit wait.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id(element_ID)));

The reference variable “wait” informs the WebDriver to wait until the Expected condition to occur (or) Wait for the specified time of 30seconds, whichever shows in the first place before throwing an exception.

Below are the ExpectedConditions:

  • AlertIsPresent()
  • ElementSelectionStateToBe()
  • VisibilityOfAllElementsLocatedBy()
  • ElementToBeSelected()
  • FrameToBeAvaliableAndSwitchToIt()
  • InvisibilityOfTheElementLocated()
  • TextToBePresentInElementLocated()
  • TextToBePresentInElementValue()
  • TitleIs()
  • TitleContains()
  • VisibilityOf()
  • VisibilityOfAllElements()
  • VisibilityOfElementLocated()
  • InvisibilityOfElementWithText()
  • ElementToBeClickable()
  • PresenceOfAllElementsLocatedBy()
  • PresenceOfElementLocated()
  • TextToBePresentInElement()

The Implicit wait is simple as compared to Explicit wait and can be declared in setup method of the test script in a single line of code. But, despite being easy and simple to apply and hence rising scope of Explicit Waits as these waits can be applied for a specified test Step in test script.

92.

What is synchronization?

Answer»

Synchronization is a mechanism that involves two or more components that work parallel with Each other.

In Test Automation, Application Under Test and Test Automation tool are the two components.

Both these components have their own speed,  and to make these two components should move with the same and desired speed, we should write our scripts in such a way that we will not encounter "Element Not Found" errors which will consume time again in debugging.

Unconditional and Conditional Synchronization are the two categories of synchronization.

Unconditional Synchronization:

In Unconditional synchronization, we specify the timeout value only. The tool will wait until a CERTAIN amount of time and then proceed further.

Examples: Wait() and Thread.Sleep(),

The disadvantage in the above statements is, even though the application is ready there is a chance of unnecessary waiting time.

When we interact with third-party systems LIKE interfaces, it is not possible to write a condition or check for a condition. In such scenarios, we have to make applications wait for a certain amount of time by specifying timeout value and the unconditional wait comes as help here.

Conditional Synchronization:

In conditional synchronization, we specify a condition along with timeout value, so the tool waits and checks for the condition and then it come out if nothing happens.

It is important to set the timeout value in conditional synchronization because the tool should proceed further instead of making the tool to wait for a particular condition to satisfy.

In Selenium implicit Wait and Explicit Wait are two components of conditional statements.

There are two types of Conditional Synchronization:

  1. Implicit Wait
  2. Explicit Wait

Implicit Wait:

Implicit Wait tells the WebDriver to before throwing exception NoSuchElement/ElementNotVisible, wait until the stated time. Waiting time between each consecutive step is taken by default across the test script. So, the next test Step will be executed only when the specified time is elapsed.

Syntax:

driver.Manage().TIMEOUTS().ImplicitlyWait(TimeSpan.FromSeconds(30));

FromMilliSecondsThe Implicit wait takes two arguments: TimeSpan (timeToWait) and time measure.

  • FromSeconds
  • FromMinutes
  • FromHours
  • FromDays  

Explicit Wait:

When page load dynamically explicit waits are good to use. Before throwing NoSuchElement (or) ElementNotVisible Exceptions, explicit Wait tells the WebDriver to Wait TILL the specified condition is met or maximum time elapses. Explicit waits are applied for the specified test Step in the test script.

We must first create an instance for the “WebDriverWait” class to use Explicit wait.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id(element_ID)));

The REFERENCE variable “wait” informs the WebDriver to wait until the Expected condition to occur (or) Wait for the specified time of 30seconds, whichever shows in first place before throwing an exception.

Below are the ExpectedConditions:

  • AlertIsPresent()
  • ElementSelectionStateToBe()
  • VisibilityOfAllElementsLocatedBy()
  • ElementToBeSelected()
  • FrameToBeAvaliableAndSwitchToIt()
  • InvisibilityOfTheElementLocated()
  • TextToBePresentInElementLocated()
  • TextToBePresentInElementValue()
  • TitleIs()
  • TitleContains()
  • VisibilityOf()
  • VisibilityOfAllElements()
  • VisibilityOfElementLocated()
  • InvisibilityOfElementWithText()
  • ElementToBeClickable()
  • PresenceOfAllElementsLocatedBy()
  • PresenceOfElementLocated()
  • TextToBePresentInElement()

The Implicit wait is simple as compared to Explicit wait and can be declared in setup method of the test script in single line of code. But, despite being easy and simple to apply and hence rising scope of Explicit Waits as these waits can be applied for a specified test Step in test script.

93.

What are the four components of Selenium?

Answer»

Below is the list of selenium components -

  • Selenium IDE
  • Selenium client API
  • Selenium WEBDRIVER
  • Selenium Remote Control
  • Selenium Grid

Selenium IDE 

Selenium IDE was created with the intention to increase the speed of test case creation. It records user action and playback which helps you create simple tests quickly. The interface is user-friendly and also supports multiple extensions.

Selenium IDE(Integrated Development Environment) is an open-source software testing TOOL for web applications and Firefox Add-on and chrome extension. Without paying a single penny Testers and web developers can use and download it. The purpose behind Selenium IDE is to increase the speed of test case creation and it allows to edit, record and debug the tests. It helps the users to record tests quickly and playback tests in the ACTUAL environment that it will run in.

Selenium client API

Selenium IDE has its very own scripting language called Selenese, which provides options for clicking a link, selecting something, retrieving data from opened pages. Instead of writing tests in Selenese, these tests can also be written in different programming languages. Tests communicate with selenium by calling methods in Selenium Client API. Selenium provides client APIs for Java, C#, Ruby, JavaScript, R, and Python. With Selenium 2, a new Client API is introduced with WebDriver as its central component.

Selenium WebDriver

Selenium WebDriver is a collection of APIs used to automate web application testing. It is a framework to automate a browser that accepts commands and sends it to the browser through browser-specific drivers. WebDriver control browser by communicating with it. Selenium WebDriver supports Firefox, Chrome, IE and Safari browsers and Java, C#, PHP, Python, Perl, Ruby programming languages. It is designed to provide a simple, CONCISE programming interface. It enables a user to use a programming language of their choice to write test scripts and enables them to use conditional operations, looping and other programming concepts which helps to make test script robust.

Selenium Remote Control

Selenium RC(Remote Control) is a tool that allows creating automated web application UI tests in any programming language.

Selenium RC is composed of two components

1. Selenium Server

It LAUNCHES and kills browsers and interprets and runs the Selenese commands passed from the test program. For browser request, Selenium server acts as an HTTP proxy by intercepting and verifying HTTP messages passed between the browser and the AUT. In short Selenium Server receives Selenium commands from your program, Server interprets commands and reports back results of running test to your program.

2. Selenium Client

Client libraries provide the interface between a programming language and the RC Server. Client libraries of different programming languages, instructs Selenium Server how to test the AUT bypassing server test script's Selenium commands.

The client libraries allow you to run Selenium commands from a program. Each supported language has a different client library. The selenium client library provides a programming interface (API) that runs Selenium commands from your program. Each interface contains a programming function that supports each Selenese command.

The client library gets Selenese command and passes it to the Selenium Server for processing a specific action on the application under test (AUT) and receives the result of that command and sends it to your program. Your program stores received result into program variable and report is a success or failure.

Selenium RC is used to execute scripts on different browsers as RC supports multiple browsers like IE, Firefox, Chrome, Safari, Opera, etc.

94.

Which Operating Systems selenium supports?

Answer»

Selenium is not a single tool but below TOOLS comes under selenium umbrella -

  • Selenium IDE
  • Selenium RC
  • Selenium WebDriver
  • Selenium Grid

As Selenium Grid is just a set of CONFIGURATIONS and Selenium RC is deprecated, let US discuss different operating SYSTEMS supported by below Selenium Components only-

  • Selenium IDE
  • Selenium WebDriver

Operating Systems supported by Selenium IDE

Latest Selenium IDE  supports below mentioned operating systems which support Firefox and chrome runs on the Chrome and Firefox Browsers:

  • Microsoft Windows
  • Linux
  • Mac OS X
  • Solaris
  • Other operating systems which support Firefox and Chrome Browsers

Operating Systems supported by Selenium WebDriver are

  • Microsoft Windows
  • Mac OS X
  • Linux

To conclude, selenium at a high level is supported by the FOLLOWING Operating Systems:

  • Microsoft Windows
  • Linux
  • Mac OS X
95.

When should we use Selenium IDE?

Answer»

Selenium IDE was created with the intention to increase the SPEED of test case creation. It records user action and playback which helps you create simple tests quickly. The interface is user-friendly and also supports multiple extensions.

Selenium IDE(Integrated DEVELOPMENT Environment) is an open-source software testing tool for web applications and Firefox Add-on and chrome extension. Without paying a single PENNY Testers and web developers can use and download it. The purpose of behind Selenium IDE is to increase the speed of test case creation and it allows to edit, record and debug the tests. It helps the users to record tests quickly and playback tests in the ACTUAL environment that it will run in. DEPENDING on your requirement for test creation, test environment and test execution you can use Selenium IDE.

96.

What are the limitations of Selenium?

Answer»

Selenium is a very widely used reliable software testing tool across the world. Many IT companies are using Selenium to meet their FAST delivery schedules. Selenium is a super-duper hit tool in the software testing field. Selenium has its own advantages but still, there are some limitations which we should know.

Let us discuss Selenium limitations one by one -

  • It only supports web applications and does not SUPPORT non-web based applications such as desktop applications or mobile applications.
  • Being open-source, for technical issues need to rely on the selenium community forum which may not give you quick and reliable solutions.
  • Some user-specific pages load different elements depending on the user, or sometimes elements appear depending on the previous ACTION taken, for example, list of cities in the DROPDOWN corresponding to the country selected in previous action loads when you select a country. Selenium may not identify elements on run time. We need to ads explicit waits in the script so the element loads properly and handle these type of scenarios.
  • Some web elements properties changes on page load. Handling these dynamic elements is a bit tricky in selenium. To handle dynamic elements, use  XPath or CSS with functions like starts-with, contains, ends with, etc.
  • Good hold on the programming language is essential for successful automation testing.
  • To work with selenium you need to have programming skills. A high skill level is expected from Selenium automation engineer.
  • No inbuilt reporting capability. You have to rely on plug-ins like JUnit and TestNG for test reports.
  • Image testing is not supported in selenium. Selenium standard API interacts with browser and it difficult to test image-based applications.
  • Test environment preparation in Selenium TAKES more time compared to other tools like UFT, RFT, Silk test, etc
  • No test tool integration for Test Management. Neither Selenium supports test management nor it could be integrated with any test management tool.
  • Selenium does not handle window based pop-ups. You need to use JavaScript Robot class a java based utility or third-party open-source tool AutoIt.
  • There is a limitation on the automating of captcha in selenium. You need to use a third-party tool to automate captcha.
97.

What are the advantages and disadvantages of Selenium IDE?

Answer»

Selenium IDE (Integrated Development ENVIRONMENT) previously known as Selenium RECORDER is the simplest tool. Selenium IDE is an automated testing tool that supports record and PLAYBACK actions.

This firefox plugin has immense benefits for test automation.

Advantages are -

  • It is an Open-Source tool
  • very easy to get started with for functional testing of web applications.
  • It enables to record and playback for testing web applications.
  • Capability to convert the test to different programming languages
  • Experience in a programming language is not required
  • Can debug and SET breakpoints
  • Available as google chrome IDE

Disadvantages are -

  • Being a firefox plugin, the scope is limited to firefox browser
  • Does not support iteration
  • Error handling is not supported
  • Database testing is not supported
  • Grouping of scripts not supported
  • Does export WebDriver script
  • Does not support data-driven scripts.
98.

What are the different methods to move back, forward and refresh a web-page ?

Answer»
  • driver.navigate().FORWARD(); – used to navigate to the next web page with reference to the browser’s history
  • driver.navigate().back(); – used to TAKE back to the previous web page with reference to the browser’s history
  • driver.navigate().refresh(); – used to to refresh the current web page i.e. reloading all the web elements
  • driver.navigate().to(“url”); – used to LAUNCH a new web browser WINDOW and navigate to the specified URL .
99.

Explain how to launch different browsers using Selenium WebDriver?

Answer»

WEBDRIVER is an Interface. We need to create an Object of the required driver class such as FirefoxDriver, ChromeDriver, InternetExplorerDriver etc.

Syntax to launch Firefox Driver: 

WebDriver driver =  new FirefoxDriver(); Also to use geckodriver with Selenium, upgrade to Selenium 3.x or HIGHER version  and SET the property as follows: System.setProperty("webdriver.gecko.driver",  "D:\\Selenium Environment\\Drivers\\geckodriver.exe");

Syntax to launch Chrome Driver: 

WebDriver driver = new  ChromeDriver();

Syntax to launch Internet Explorer Driver: 

WebDriver driver = new  InternetExplorerDriver();

Syntax to launch Safari Driver: 

WebDriver driver = new  SafariDriver();
100.

What are the different Locators supported in Selenium?

Answer»

Selenium WEB driver uses below 8 locators to find the elements on the web page:

  • id – used to SELECT the element with a SPECIFIED @id attribute.
  • name – used to Select the first element with the specified @name attribute.
  • linkText - used to select link /anchor tag element which CONTAINS the matching TEXT
  • PartialLinkText – used to select link (anchor tag) element which contains text matching the specified partial link text.
  • tagName – used to locate the element using its HTML Tag
  • className – used to locate the Element using a class Name
  • cssSelector - used to locate the element using CSS selectors
  • xpath – used to locate the element using an XPath expression.