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.


Sunday, November 18, 2018

Different Types of Exceptions in Selenium WebDriver - Selenium WebDriver Tutorial

In this tutorial, I am going to cover how to handle exceptions in Selenium WebDriver.



Topics to be covered -


  • What is Exception?
  • Different WebDriver Exceptions.







Exceptions in WebDriver







What is Exception?

An exception is an event that occurs during the execution of a program. It interrupts the normal flow of execution of the program.

Whenever an exception occurs the system creates an exception object that contains detailed information of the exception and throws it i.e., it halts the normal execution flow and displays information about the exception on the console window.

If we do not want such abnormal termination of the execution of the program, handling these exceptions is necessary.

Handling exception means to avoid abnormal halts of the program flow and allowing the execution of the program even after the occurrence of an exception. This ensures the execution of the entire program.



Different Exceptions in Selenium WebDriver - 

Below is the list of most commonly exceptions occurred while creating Selenium Webdriver scripts - 
  • ElementNotVisibleException.
  • ElementNotSelectableException.
  • NoSuchElementException. 
  • ElementNotClickableException.
  • NoSuchFrameException.
  • NoAlertPresentException.
  • NoSuchWindowException.
  • TimeoutException.
  • WebDriverException.
  • SessionNotFoundException.


1. NoSuchElementException - This exception occurs when you are trying to locate an element using wrong locators.

In case if you don't know how to locate an element in Selenium follow the link below - Locating the elements in Selenium










In the above images, we are trying to inspect 'Email or Phone' field of the Facebook application whose locator is - id="email" 




 package com.sessions;  
   
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
   
 public class SeleniumExceptions {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           driver.get("https://www.facebook.com");//launch facebook application.  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           driver.findElement(By.id("email123")).sendKeys("abcd1234");  
   
   
      }  
   
 }  
   


Note In the above program we used id="email123" which is a wrong locator so you will get below exception -






2. NoAlertPresentException - This exception occurs when you are trying to switch to an alert/pop-up window which is not available.


 package com.sessions;  
   
 import org.openqa.selenium.Alert;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
   
 public class SeleniumExceptions {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           driver.get("https://www.facebook.com");//launch facebook application.  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           Alert alert = driver.switchTo().alert();  
   
   
      }  
   
 }  
   


Note - In the last statement of the above program we are trying to switch to an alert after opening the login page of Facebook. But there is no such alert window appears when you open the Facebook application. So you will get below exception -







3. NoSuchFrameException - This exception occurs when you are trying to switch to a frame which is not available.


 package com.sessions;  
   
 import org.openqa.selenium.Alert;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
   
 public class SeleniumExceptions {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           driver.get("https://www.facebook.com");//launch facebook application.  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           driver.switchTo().frame("framename");  
   
   
      }  
   
 }  
   



Note - In the last statement of the above program we are trying to switch to a frame after opening the login page of Facebook. But there is no such frame when you open the Facebook application. So you will get below exception -






4. NoSuchWindowException - This exception occurs when you are trying to switch to a window which is not available.


 package com.sessions;  
   
 import org.openqa.selenium.Alert;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
   
 public class SeleniumExceptions {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           driver.get("https://www.facebook.com");//launch facebook application.  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           driver.switchTo().window("Homepage");  
   
   
      }  
   
 }  
   


Note - In the last statement of the above program we are trying to switch to a window "Homepage" after opening the login page of Facebook. But there is no such window when you open the Facebook application. So you will get below exception -








5.  NoSuchSessionException - This exception occurs when the driver is performing any action after immediately quitting the browser.




 package com.sessions;  
   
 import org.openqa.selenium.Alert;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
   
 public class SeleniumExceptions {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           driver.get("https://www.facebook.com");//launch facebook application.  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           driver.quit();  
             
           driver.findElement(By.id("email"));  
   
   
      }  
   
 }  
   


Note - In the last statement of the above program we are trying to locate 'Email or Phone' text field after quitting the browser. So you will get below exception -





6. ElementNotVisibleException - An element is present in the HTML structure but it is not visible on the web-page because it is hidden.

Hidden elements are defined in the HTML using type='hidden'.


7. ElementNotSelectableException - An element is present in the HTML structure but it is disabled(cannot click or select) on the web-page.


8. StaleElementRefrenceException - The referenced element is no longer present on the DOM page (a reference to an element is now Stale). E.g. The Element belongs to a different frame than the current one OR the user has navigated away to another page.

9. TimeoutException - This Exception occurs when the driver fails to locate an element in the specified time in the script.


 package com.sessions;  
   
 import java.util.concurrent.TimeUnit;  
   
 import org.openqa.selenium.Alert;  
 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.ExpectedConditions;  
 import org.openqa.selenium.support.ui.Wait;  
 import org.openqa.selenium.support.ui.WebDriverWait;  
   
 public class SeleniumExceptions {  
   
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
             
           WebDriver driver = new ChromeDriver();  
             
           WebDriverWait wait = new WebDriverWait(driver,10);  
             
     driver.get("https://www.facebook.com");//launch facebook application.  
             
           driver.manage().window().maximize();//maximizing browser.  
             
           WebElement email = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email123")));  
             
           email.sendKeys("abcsd2344");  
             
             
             
   
   
      }  
   
 }  
   


Note - In the above program we have specified 10 seconds time. We are trying to locate 'email' element with the wrong locator 'email123'. So if within 10 seconds the driver will not be able to locate the element, it will throw below exception -




That's all!!! 

Please give your comment below if you have any doubt.

Sunday, November 11, 2018

How to use Locators in selenium WebDriver | Selenium Tutorial for beginners

In this tutorial, I am going to cover different types of locators used in Selenium scripts to identify web-elements on the web-page.


Topics to be covered - 
  • What is locator?
  • Different types of locators.
  • How to identify locators and how to use them to locate web-elements.


Locators






Locators are the property-value pairs or attributes of the web-elements in HTML document structure. They are used to identify web-element on the web-page. They give the exact location of the web-elements on the web-page. We can say that the locators provide the address of web-elements on the Web-Page.


Different Locators - 
  • Id 
  • Name
  • ClassName
  • PartialLinkText
  • Linktext
  • X-Path
  • CSS
  • TagName

Note - I will take the Facebook application to explain the concept of locators.


Locate Element by Id - 

Step 1 - Launch Facebook application.

Step 2 - Inspect 'Password' field.




To inspect a web-element, right click on it and select 'inspect' option. Developer tools will be opened highlighting the attributes of the web-element. 




We can notice the highlighted portion in the above image. There is one attribute, id="pass". This 'id' is nothing but the Id locator that can be used in the selenium script to locate the 'Password' field as shown below.


 driver.findElement(By.id("pass"));  



Locate Element by Name -


Step 1 - Launch Facebook application.

Step 2 - Inspect 'email or phone' field.




We can notice the highlighted portion in the above image. There is one attribute, name="email". This 'name' is nothing but the Name locator that can be used in the selenium script to locate the 'email or phone' field as shown below.


 driver.findElement(By.name("email"));  



Locate Element by TagName -


TagName locator does not locate a specific element on the web-page but it locates a set of the same sort of web-elements on the web-page. 

For example - All the text field on the web-page, all the links on the web-page and so on.


Step 1 - Launch Facebook application.

Step 2 - Locate all the links in the application.

Step 3 - Print name of all the links and the total number of links on the console window.



1:  package com.sessions;  
2:    
3:  import java.util.List;  
4:    
5:  import org.openqa.selenium.By;  
6:  import org.openqa.selenium.WebDriver;  
7:  import org.openqa.selenium.WebElement;  
8:  import org.openqa.selenium.chrome.ChromeDriver;  
9:    
10:  public class Links {  
11:    
12:       public static void main(String[] args) {  
13:            System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
14:              
15:            WebDriver driver = new ChromeDriver();  
16:              
17:            driver.get("https://www.facebook.com");//launch facebook application.  
18:              
19:            driver.manage().window().maximize();//maximizing browser.  
20:              
21:            //Storing all the links available on the application  
22:            List<WebElement> links = driver.findElements(By.tagName("a"));  
23:              
24:            //Printing total number links on the FB application  
25:            System.out.println(links.size());  
26:              
27:            //Printing name of all the links on the application  
28:            for(WebElement link : links)  
29:            {  
30:                 System.out.println(link.getText());//getText() is used to get the text of the web-element.  
31:            }  
32:    
33:    
34:       }  
35:    
36:  }  
37:    

Note -

  • Link in HTML document is represented by <a> tag.
  • Line number 21 shows the use of TagName in the Selenium script. Here 'a' is the tag name of the link.
  • At line number 22, we used  List<WebElement> to store all the links. Since there are many links, so findElements() command is used instead of findElement() to locate all the links.
  • To use List, we need to import - java.util.list; and for WebElement - org.openqa.selenium.WebElement;
  • The list is an important concept of Java which is used to store and manipulate a set of similar type of objects. In our case we stored web-elements.



Locate Links on the Web-Page -

Link basically refers to the URL of the other web-page. Once clicked will open the web-page either on the same window or in a new window. 






Note - Link in HTML document is represented by <a> tag.


Selenium provides two locators to locate Links on the web-page -


1. LinkText - It uses the full-text name of the link to locate it on the web-page.


Step 1 - Launch Facebook application.

Step 2 - Locate 'Forgotten account' link as shown in the image above.

Step 3 - Click on it.
As we can see in the above image 'a' tag representing the link and 'forgotten account?' is the name of the link.


1:  package com.sessions;  
2:    
3:  import java.util.List;  
4:    
5:  import org.openqa.selenium.By;  
6:  import org.openqa.selenium.WebDriver;  
7:  import org.openqa.selenium.WebElement;  
8:  import org.openqa.selenium.chrome.ChromeDriver;  
9:    
10:  public class Links {  
11:    
12:       public static void main(String[] args) {  
13:            System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
14:              
15:            WebDriver driver = new ChromeDriver();  
16:              
17:            driver.get("https://www.facebook.com");//launch facebook application.  
18:              
19:            driver.manage().window().maximize();//maximizing browser.  
20:              
21:            //Locating the link and clicking on it.  
22:              
23:            driver.findElement(By.linkText("Forgotten account?")).click();  
24:    
25:    
26:       }  
27:    
28:  }  
29:    




2. PartialLinkTextIt uses the partial-text name of the link to locate it on the web-page.

Here we will use only a part of the link text to locate it.

For Example -

 Link name - 'Forgotten account?' 

We will use only 'Forgotten' to locate the link as shown in the below code.



1:  package com.sessions;  
2:    
3:  import java.util.List;  
4:    
5:  import org.openqa.selenium.By;  
6:  import org.openqa.selenium.WebDriver;  
7:  import org.openqa.selenium.WebElement;  
8:  import org.openqa.selenium.chrome.ChromeDriver;  
9:    
10:  public class Links {  
11:    
12:       public static void main(String[] args) {  
13:            System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
14:              
15:            WebDriver driver = new ChromeDriver();  
16:              
17:            driver.get("https://www.facebook.com");//launch facebook application.  
18:              
19:            driver.manage().window().maximize();//maximizing browser.  
20:              
21:            //Locating the link and clicking on it.  
22:              
23:            driver.findElement(By.partialLinkText("Forgotten")).click();  
24:    
25:    
26:       }  
27:    
28:  }  
29:    



One thing is common in LinkText and PartialLinkText

If there are two links having the same link-text, above both the locators will locate the first link always.

So what if a user wants to click on the non-first link?

In such a scenario, we can use X-Path or CSS selector.




That's all guys!!! 

Please post your queries related to Selenium Locators.

Next Tutorial - X-Path in Selenium




Sunday, November 4, 2018

Handling Frames in Selenium WebDriver | Selenium Tutorial

In this tutorial, I am going to cover how to handle Frames available on WebPages in Selenium WebDriver.


Topics To Be Covered -

  • What is Frame?
  • How to switch to Frame?
  • Different ways to identify Frame on web-pages.
  • How to navigate one Frame to another on the same web-pages?
  • How to get the total number of Frames on web-pages?

Frames in Selenium  








The HTML Frames are used to divide the web-page/browser window into different multiple sections where each section may or may not displays contents of the same web-page. It means each section can load the content of other websites also. 


How to inspect Frames on web-pages -



Here, I will take the website - 'https://seleniumhq.github.io/selenium/docs/api/java/' to explain the concept.



  • If you open the above URL, you will get above page. You can notice the entire page is divided into 3 sections. First two sections are at the left side and the third section at the right of the first two sections.
  • Right-click on the section highlighted in green on the below image and click on 'inspect' option.

  • Developer tools will be opened highlighting the property of the inspected element - 

  • Expand the developer tools upward and then scroll up until you get below result - 

  •  We can notice <frame> tag below the <head> tag. Inside the <frame> tag, we can get the 'Frame Name'. In our case, frame name is 'packageListFrame'.
Note - Similarly, we can get the other frames'name.

Handle Frames in Selenium Script - 

To handle frames, Selenium WebDriver provides a method - 
  • driver.switchToFrame(parameter);

Note -

We pass 'parameter' in the form of -
  1.  'Index of the Frame'
  2.  'Frame Name' and 
  3. ' Frame as WebElement'. 

Scenario 1 - 

  • Open 'https://seleniumhq.github.io/selenium/docs/api/java/' in chrome.
  • Click on 'com.thoughworks.selenium' link.


 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the target link.  
      }  
 }  


Note - Here we are trying to click on the link which is inside 'packageListFrame'. So if we run above program, we will get below compilation error -



NoSuchElementExpeption.



Scenario 2 - 

  • Open 'https://seleniumhq.github.io/selenium/docs/api/java/' in chrome.
  • Switch to the above-identified Frame.
  • Click on 'com.thoughworks.selenium' link.


 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           driver.switchTo().frame("packageListFrame");//Switching to the target frame  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the target link.  
      }  
 }  


Note - Here we first switched to the frame then click on the link. So the program will run successfully.


Point to Note -

  • We can also switch to Frame using its index. Indexing of frame starts with '0', '1','2' and so on. So the index of the first frame is '0'. Therefore, the above program can be run as - 
 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           driver.switchTo().frame(0);//Switching to the target frame  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the target link.  
      }  
 }  


Note - Here we switched to the frame using its Index.


  • We can also switch to frame - first identifying the frame as a web-element and then switching to it. Here we will use x-path to locate the frame on the web-page. This is the most reliable method to switch to the frame. The above-described two methods use 'Frame Name' and 'Frame Index' to locate the Frame. But suppose, the name of the frame got changed or due to the insertion of the new frame on the web-page, the position of the frame got changed. But, this third method uses x-path to locate the frame.X-path directly locates the element wherever it is available on the web-page. It does not require any index or name to locate the element. That is why this method is more reliable.
Below image describes the x-path of the frame.


 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           WebElement frame_element = driver.findElement(By.xpath("//frame[@name='packageListFrame']"));//locating the frame element in order to switch to it.  
           driver.switchTo().frame(frame_element);//Switching to the target frame  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the target link.  
      }  
 }  


Note - Here we first located the frame on the webpage using x-path and then stored in the 'frame_element' variable. Since 'frame_element' is pointing to the frame, we used this as the parameter to switch to the frame in the above program.


How to switch from one frame to another -


To switch from one frame to another, Selenium WebDriver provided two methods -

  • driver.switchTo().defaultContent()
  • driver.switchTo().parentFrame()

This is possible to switch from one frame to another. However, We cannot directly switch from one frame to another. As we know a web-page/browser window is divided into multiple frames. Here web-page/browser window is the main window which contains those multiple frames. Frames are independent of each other. So if we are already switched to a frame then first we need to switch from this frame to the main window then we can switch to the other frames from there. The similar concept applies when a frame is itself divided into multiple frames.


Scenario 3 - 

  • Open 'https://seleniumhq.github.io/selenium/docs/api/java/' in chrome.
  • Switch to the First frame(packageListFrame).
  • Click on 'com.thoughworks.selenium' link.
  • Switch to the Second Frame(packageFrame), highlighted in the below image in green color.



 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           driver.switchTo().frame("packageListFrame");//Switching to the target frame  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the target link.  
           driver.switchTo().frame("packageFrame");//Switching to the second frame  
      }  
 }  


Note - System will throw NoSuchFrameException while switching to the second frame as shown below.


Scenario 4 - 

  • Open 'https://seleniumhq.github.io/selenium/docs/api/java/' in chrome.
  • Switch to the First frame(packageListFrame).
  • Click on 'com.thoughworks.selenium' link.
  • Switch to the main window.
  • Switch to the Second Frame(classFrame).
  • Click on 'org.openqa.selenium' link highlighted in green color.


 package com.sessions;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           driver.switchTo().frame("packageListFrame");//Switching to the first frame  
           driver.findElement(By.xpath("//a[text()='com.thoughtworks.selenium']")).click();//Clicking on the first target link.  
           driver.switchTo().parentFrame();//Switching to the main window.  
           driver.switchTo().frame("packageFrame");//Switching to the second frame  
           driver.findElement(By.xpath("//span[text()='Action']")).click();// clicking on the second target link.  
      }  
 }  


How to count total number frames available in web-page - 


 package com.sessions;  
 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;  
 public class SeleniumFrame {  
      public static void main(String[] args) {  
           System.setProperty("webdriver.chrome.driver", "F:\\software\\chromedriver_win32\\chromedriver.exe");  
           WebDriver driver = new ChromeDriver();  
           driver.get("https://seleniumhq.github.io/selenium/docs/api/java/");  
           driver.manage().window().maximize();//maximizing browser.  
           List<WebElement> frame_count = driver.findElements(By.tagName("frame"));  
           System.out.println(frame_count.size());  
      }  
 }  


Note -

  •  Every frame in HTML structure starts with <frame> tag. So 'tagName' locator is used to locate frames in the web-page. 
  • findElements0 - returns List of WebElement.
  • frame_count - refers to all the frames available on the web-page.
  • size() - returns number of  elements referred by frame-count.

That all guys!!! 



Do comment in the comment box and share your views about the post. If you have any query, please comment on it. It will help me to reach to you and help you to resolve your query.