Saturday, December 22, 2018

Top 10 Selenium Interview Questions And Answers - Part 1


Hello guys, In this blog I am going to provide most frequently asked selenium-related interview questions and answers in part-wise.




Part 1


1. How to handle dynamic elements in Selenium?

Solution – We can use x-path along with contains(), starts-with(), ends-with() methods –   
                    depends on the scenario.     

Example

Let’s say, ‘Id’ of a username field is – username_123
If you open the page again, then Id is showing as - username_245

That’s mean, the first part – username is static, whereas, second part after underscore is dynamic.

x-path for such scenario will be =  //*[contains(@id ,’username’)]

Since the starting text is static, the above scenario can also be handled using starts-with() method.

x-path = //*[starts-with(@id ,’username_’)]


Let’s say, ‘Id’ of a username field is – 123_username
If you open the page again, then Id is showing as – 245_username

Here the latter part is static.

X-path = //*[ends-with(@id ,’_username’)]


2.  Give an example of Method overloading in Selenium.

Solution -  Example can be switching to Frames.

·         frame(int index)
·         frame(string frame_name)
·          frame(WebElement element)


1   3.  How do you achieve synchronization in Selenium?
S
S   Solution – driver.manage().timeOuts().implicitlyWait(10, OutputType.SECONDS);
It 
il      It will ask the web driver to wait for 10 seconds before throwing an exception in case any web driver is unable to locate any element. It is applicable to every command written in the script.


1
   4. How to invoke an application in web driver?

S   Solution –

·         driver.get(“application_url”);

·         driver.navigate().To(“application_url”);


1  5. How to get the width and height of the textbox?
     Solution –

·         driver.findElement(By.xpath(“locator”)).getSize().getWidth();
·         driver.findElement(By.xpath(“locator”)).getSize().getHeigtht();



  
    6. Difference between Assert, Verify and WaitFor commands.
S
o   Solution –

·         Assert – It checks whether an element is on the page or not. If the element is not present, then the test will fail, and execution will stop at that point only.
·         Verify - It checks whether an element is on the page or not. If the element is not present, then the test will fail, but execution will continue until the last command of the script.
·         WaitFor – It waits for the specified amount of time so that the element may be available on the page. But if the element is not available within the specified amount of time, then the test will fail at that point only.


7.  Different ways to refresh the browser.

S     Solution –

·         Driver.navigate().refresh();
·         Driver.navigate().to(driver.getCurrentUrl());
·         Driver.get(driver.getCurrentUrl());



1  8. Different exceptions encountered in Selenium WebDriver.
S
S    Solution -  Below are some most encountered Exceptions that occur while creating Selenium Automation Script.

  •     NoSuchFrameException
  •     AlertNotPresentException. 
  •     NoSuchElementException.
  •     ElementNotVisibleException.
  •      NOSuchWindowException.
  •       TimeOutException.
         
         To get a detailed explanation, follow the linkExceptions In Selenium


    9. What is the alternate way to click on the Login button?

S   Solution –

                    submit() – But can be used only when attribute ‘type=submit’.

1
    10. What is the purpose of getOptions() methods?
S    
o      Solution – It is used to get all the selected options from the dropdown list.

                             Return Type -  List<WebElement>

       
      Below program will print all the options of the Country drop-down


 package com.javascript;  
   
 import java.util.List;  
   
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.support.ui.Select;  
   
 public class GetOption {  
   
      public static void main(String[] args) {  
             
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");   
            WebDriver driver = new ChromeDriver();   
            driver.get("http://newtours.demoaut.com/mercuryregister.php");   
            driver.manage().window().maximize();  
              
            Select select = new Select(driver.findElement(By.xpath("//select[@name='country']")));  
            List<WebElement> options = select.getOptions();  
            for(WebElement option : options)  
            {  
                 System.out.println(option.getText());  
            }  
              
   
      }  
   
 }  
   

Thursday, November 29, 2018

Actions in Selenium | Keywords And Mouse Events Using Actions Class In Selenium WebDriver

In this tutorial, I am going to cover how to handle keyboard and mouse events using Actions classes in Selenium.




Topics to be covered
  • What is Keyboard and Mouse events?
  • Actions class in Selenium.
  • How to handle different keyboard and mouse events using Actions class in Selenium?



Actions 







There are various kinds of Keyboard and Mouse events such as - 
  • Drag and drop.
  • Right click.
  • Double click.
  • MouseOver.
and so on.

Such events are handled using advanced user interactions APIs. It contains Action and Actions classes to handle such events.

In Selenium, we will use Actions class to perform such events while automating.

In order to use Actions class, we need to import one package

 org.openqa.selenium.interactions.Actions;  


We will use the Mercury Tours application to demonstrate keyboard and mouse events.






#1 MouseOver - In this event, only the mouse is moved over a web-element but not clicked.

To handle MouseOver, Actions class provides a method

  • movetoElement(WebElement element); -> element indicates on which element MouseOver will be performed.
Note - moveToElement() will just inform that on which element mouseOver will be done. It will not move the mouse over that element.

To achieve it, Actions provides two methods- 
  • perform() - It completes an action which is intended to achieve. It is used when the user wants to perform a single action.
  • build() - If the user wants to perform multiple actions on an element at a time, it is used. It compiles all the actions as a single one. It is followed by perform() methods.

-> These two methods are applicable to all the events mentioned above. 

-> We will get a clear picture when we do programming.


 package com.sessions;  
   
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.interactions.Actions;  
   
 public class keyboard_Mouse_Events {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           driver.get("http://newtours.demoaut.com/");  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           //Creating Actions Class Object  
           Actions act = new Actions(driver);  
             
           //Locating the element to perform mouse over.  
           WebElement element = driver.findElement(By.xpath("//input[@name='login']"));  
             
           //Performing mouse over on the element.  
           act.moveToElement(element).perform();  
             
           }  
   
 }  
   


Explanation - 
  • In this program, We are performing mouse over on the 'Login' button of Mercury Tours application highlighted in the above image.
  • 'element' variable is pointing to the 'Login' button.
  • We have used perform() method as we are performing only single action.
  • Since it is just doing mouse over operation on the 'Login' button. So we can't visualize it.



#2 Right Click - This event performs a right-click operation as we normally do with the mouse.

->Actions class provides two methods to achieve it - 

  • contextClick(WebElement element); --> element indicates on which element Right-Click will be performed.
  • contextClick(); --> To perform right-click operation on the web-page.


 package com.sessions;  
   
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.interactions.Actions;  
   
 public class keyboard_Mouse_Events {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           driver.get("http://newtours.demoaut.com/");  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           //Creating Actions Class Object  
           Actions act = new Actions(driver);  
             
           //Locating the element to perform right-click.  
           WebElement element = driver.findElement(By.xpath("//input[@name='login']"));  
             
           //Performing right-click action on the element.  
           act.contextClick(element).perform();  
             
             
           }  
   
 }  
   


Explanation - 
  • In this program, We are performing right-click on the 'Login' button of Mercury Tours application highlighted in the above image.
  • 'element' variable is pointing to the 'Login' button.
  • We have used perform() method as we are performing only single action.



#3 Double Click - This event performs a double-click operation as we normally do with the mouse.

->Actions class provides two methods to achieve it - 

  • doubleClick(WebElement element); --> element indicates on which element double-Click will be performed.
  • doubleClick(); --> To perform double-click operation on the web-page.

 package com.sessions;  
   
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.interactions.Actions;  
   
 public class keyboard_Mouse_Events {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           driver.get("http://newtours.demoaut.com/");  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           //Creating Actions Class Object  
           Actions act = new Actions(driver);  
             
           //Locating the element to perform double-click.  
           WebElement element = driver.findElement(By.xpath("//font[text()='Password:']"));  
             
           //Performing double-click action on the element.  
           act.doubleClick(element).perform();  
             
             
           }  
   
 }  
   









Explanation - 
  • In this program, We are performing double-click on the 'Password' text of Mercury Tours application highlighted in the above image.
  • 'element' variable is pointing to the 'Password' text.
  • We have used perform() method as we are performing only single action.
  • After performing the action, 'Password' text will be highlighted in blue.



#4 Drag And Drop - This event drags one element from the source location and drops it to the target location.

->Actions class provides two ways to achieve it -

  1. clickAndHold(source_element).moveToElement(target_element).release().build().perform();
  2. dragAndDrop(source_element,target_element);

First Approach - 

 package com.sessions;  
   
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.interactions.Actions;  
 import org.openqa.selenium.support.ui.ExpectedConditions;  
 import org.openqa.selenium.support.ui.WebDriverWait;  
   
 public class keyboard_Mouse_Events {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           driver.get("https://jqueryui.com/droppable/");  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           //Creating Actions Class Object  
           Actions act = new Actions(driver);  
             
           //Waiting for the frame to be available and switching to it.  
           WebDriverWait wait = new WebDriverWait(driver,10);  
           WebElement frame= driver.findElement(By.xpath("//iframe[@class='demo-frame']"));  
           wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frame));  
             
           //Locating the element to drag.  
           WebElement drag_element = driver.findElement(By.xpath("//div[@id='draggable']"));  
             
           //Locating the element to drag.  
           WebElement drop_element = driver.findElement(By.xpath("//div[@id='droppable']"));  
             
           //Performing drag and drop  
           act.clickAndHold(drag_element).moveToElement(drop_element).release().build().perform();  
             
           }  
   
 }  
   






Explanation - 
  • In this program, We are performing drag and drop operation as shown in the above image.
  • These drag and drop elements are available under a frame. So we first switched to the frame by locating it. We waited for the frame to be available then switched to it.
  • 'drag_element' variable is pointing to the element to be draggable.
  • 'drop_element' variable is pointing to the element to be droppable.
  • We have used build().perform() method as we are performing three operations.
  • clickAndHold() -> It will click on the source element and hold it.
  • moveToElement() -> It will move the hold element to the specified target element.
  • release() -> It will release the hold element to the target element.



Second Approach  -

 package com.sessions;  
   
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.interactions.Actions;  
 import org.openqa.selenium.support.ui.ExpectedConditions;  
 import org.openqa.selenium.support.ui.WebDriverWait;  
   
 public class keyboard_Mouse_Events {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           driver.get("https://jqueryui.com/droppable/");  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           //Creating Actions Class Object  
           Actions act = new Actions(driver);  
             
           //Waiting for the frame to be available and switching to it.  
           WebDriverWait wait = new WebDriverWait(driver,10);  
           WebElement frame= driver.findElement(By.xpath("//iframe[@class='demo-frame']"));  
           wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frame));  
             
           //Locating the element to drag.  
           WebElement drag_element = driver.findElement(By.xpath("//div[@id='draggable']"));  
             
           //Locating the element to drag.  
           WebElement drop_element = driver.findElement(By.xpath("//div[@id='droppable']"));  
             
           //Performing drag and drop  
           act.dragAndDrop(drag_element, drop_element).build().perform();  
             
           }  
   
 }  
   


Explanation -

  • dragAndDrop(source, target) -> It will drag the specified source element and drop it to the specified target element.







Saturday, November 24, 2018

How To Handle Multiple Windows Using Selenium WebDriver | Multiple Browser Windows In Selenium

In this tutorial, I am going to discuss how to handle multiple windows using Selenium WebDriver.




Topics to be covered - 
  • Multiple windows concept.
  • Handle multiple windows using Selenium WebDriver.


Handle Multiple Windows In Selenium






Let's take the example of Login page of Facebook Application.






There is one link 'Cookie Policy' as highlighted in the above image. 

If we click on the link, what will happen?

It will open in the new window. That's mean we have two opened windows now.

This is the concept of multiple windows. 

Now the question is, how to go to that second window and perform actions as required while automating the script?

Solution - We need to switch to that second window like we do while handling alert/frames and then we can perform required actions.


There are two methods in Selenium WebDriver to handle multiple windows - 
  • driver.getWindowHandle() - It returns the control of current opened window.
          Return type - String

  • driver.getWindowHandles() - It returns the control of all the opened windows so that we can iterate over the all the windows.
           Return Type - Set<String>


Selenium WebDriver provides one command in order to switch to the expected window -  switchTo().window("window_name");


Scenario - 
  1. Open the Login Page of the Facebook application (Main Window).
  2. Get the control of the currently opened window.
  3. Click on the "Cookie Policy" link.
  4. Now get the control of all the opened windows.
  5. Switch to the second window (Second Window).
  6. Get the title of the page.
  7. Switch back to the main window.

 package com.sessions;  
   
 import java.util.Iterator;  
 import java.util.Set;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
   
   
 public class MultipleWindows {  
   
      public static void main(String[] args) throws InterruptedException {  
             
     System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
             
           //Facebook application opened  
           driver.get("http://www.facebook.com/");  
             
           //window is maximized  
           driver.manage().window().maximize();  
             
           //control of main window is taken  
           String parentwindow = driver.getWindowHandle();  
             
           //"Cookie Policy" link is identified and clicked on it  
           driver.findElement(By.partialLinkText("Cookie")).click();  
             
           //control of all the opened window is taken  
           Set<String> windows = driver.getWindowHandles();  
             
           //logic to switch to the the expected window  
           Iterator<String> iterator = windows.iterator();  
           while(iterator.hasNext())  
           {  
                  
           String chid = iterator.next();  
           if(!parentwindow.equalsIgnoreCase(chid));  
           {  
                driver.switchTo().window(chid);  
           }  
                  
           }  
             
           //Waiting on the expected window for the specified time to observe the flow  
           //Thread.sleep() - Throws expection. It will ask to handle it while writting the command.   
           Thread.sleep(5000);  
             
           //Title of the expected page is displayed on the console  
           System.out.println(driver.getTitle());  
             
           //switching back to the main window  
           driver.switchTo().window(parentwindow);  
             
   
      }  
   
 }  
   


Explanation of below code

  • 'windows' - refers to all the opened windows. 
  • Using the concept of Iterator interface and its iterator() method, to iterate over all the opened windows.
  • Checking whether newly opened window apart from the main window(parent window).
  • If yes, then switching to the newly opened window(child window).
Note - To understand the concept of Iterator Interface, refer the link - Iterator




           Set<String> windows = driver.getWindowHandles();  
             
           Iterator<String> iterator = windows.iterator();  
           while(iterator.hasNext())  
           {  
                  
           String chid = iterator.next();  
           if(!parentwindow.equalsIgnoreCase(chid));  
           {  
                driver.switchTo().window(chid);  
           }  


Point to Note 

If there are multiple windows opened and the user wants to go to the 3rd window, above logic won't work.

How to achieve it?

Solution - We have to convert Set<String> to ArrayList<String>.

If you are not aware of the concept of ArrayList, refer the link - ArrayList

We will do the above program using ArrayList.


 package com.sessions;  
   
 import java.util.ArrayList;  
 import java.util.Iterator;  
 import java.util.Set;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
   
   
 public class MultipleWindows {  
   
      public static void main(String[] args) throws InterruptedException {  
             
     System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
             
           //Facebook application opened  
           driver.get("http://www.facebook.com/");  
             
           //window is maximized  
           driver.manage().window().maximize();  
             
           //control of main window is taken  
           String parentwindow = driver.getWindowHandle();  
             
           //"Cookie Policy" link is identified and clicked on it  
           driver.findElement(By.partialLinkText("Cookie")).click();  
             
           //control of all the opened window is taken  
           Set<String> windows = driver.getWindowHandles();  
             
           //Converting List to ArrayList  
           ArrayList<String> tabs = new ArrayList<String>(windows);  
             
           /*Switching to the expected window  
            get(index) -> Here index starts from 0,1,2,3,4 and so on.  
            '0' represents parent window.*/  
           driver.switchTo().window(tabs.get(1));  
             
           //Waiting on the expected window for the specified time to observe the flow  
           //Thread.sleep() - Throws exception. It will ask to handle it while writing the command.   
           Thread.sleep(5000);  
             
           //Title of the expected page is displayed on the console  
           System.out.println(driver.getTitle());  
             
           //switching back to the parent window  
           driver.switchTo().window(tabs.get(0));  
             
   
      }  
   
 }  
   



Similarly, if we want to go to the 3rd window, simply write -

-> driver.switchTo().window(tabs.get(2));



That's all guys!!! This is all about how to handle multiple windows using Selenium WebDriver.


If you like this post, please share your views in the comment box. If you have any doubt, I will be grateful to help you all.