Sunday, November 8, 2015

Performing drag-and-drop operation

In Selenium WebDriver, dragAndDrop method available in Actions class. Actions class supports all advanced user interactions such as firing mouse and keyboard events on a web page.

Below is the sample logic to perform drag and drop operation on a page using Actions class.


    WebElement elementToDrag = driver.findElement("DragThis"));
    WebElement elementToDropAt = driver.findElement("DropHere"));
    Actions action = new Actions(driver);
    action.dragAndDrop(elementToDrag, elementToDropAt).perform();

dragAndDrop method in actions class accepts two parameters as input. One is the element to drag and another one is the destination to drop element.

Related Topic
Advanced User Interactions API

Saturday, November 7, 2015

Reading CSV, XLS files using java

 A CSV is a comma separated values file, which allows data to be saved in a table structured format. If we get each row stored in csv file as array we can easily get the required values using index.

There is one open-source jar to parse csv file which will make our job so simple


opencsv is a simple CSV Parser for Java under a commercial-friendly Apache 2.0 license. Download it from below location.

OpenCSV : Download


JExcelApi is a java library which provides the ability to read, write, and modify Microsoft Excel spreadsheets.
JXL ; Download

After downloading the jars, include it in your classpath.
In Eclipsr IDE,
  • Right click on project
  • Build Path => Configure build path..

  • Libraries => Add External jar => Select the above downloaded jar file
  • Click Ok. Now It is ready to use in your eclipse.

Here is the content of my csv file & xls file

Here is the Java Code to read csv, xls files.

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import com.opencsv.CSVReader;

public class FileReading {
    public static void main(String[] args){
        List xls=getRowsFromXLSFile("/home/test/Contacts.xls");
        for(String eachRow[]:xls) {
       List csv=getRowsFromCSVFile("/home/test/Contacts.csv");
       for(String eachRow[]:csv) {
     * Method to read all rows from csv file using opencsv
     * @param path filePath
     * @return list of String arrays
    public  static List getRowsFromCSVFile(String path)
         List list=new LinkedList();
            CSVReader csvReader = new CSVReader(new FileReader(new File(path)));
            list = csvReader.readAll();
        catch(Exception e)
        return list;
     * Method to read all rows from xls file using jxl
     * @param path filePath
     * @return list of String arrays 
    public static List getRowsFromXLSFile(String path) // Print and get
     List rows=new LinkedList();
         File inputWorkbook = new File(path);
         Workbook workbook = Workbook.getWorkbook(inputWorkbook);
         Sheet sheet = workbook.getSheet(0);
         int maxCols=sheet.getColumns();
         int maxRows=sheet.getRows();
      for(int i=0;i<maxRows;i++) {
         String erows[] = new String[maxCols];
         int k=0;
         for(int j=0;j<maxCols;j++) {
             Cell cell1 = sheet.getCell(j,i);
    } catch(Exception e){
    return rows;

//Here is output for above file
[Name, email, phone]
[Jhon,, 234789234]
[Smith,, 234728934]
[Jack,, 234234234]
[Name, email, phone]
[Jhon,, 234789234]
[Smith,, 234728934]
[Jack,, 2394728394]

Sending mail from Gmail using WebDriver

Gmail is the mostly used mail client. Here is the logic to send a mail from gmail using WebDriver.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.concurrent.TimeUnit;

public class SendMailFromGmail {

 public static void main(String[] args) {
  String userName="<User name>";
  String password ="<password>";
  String toAddress="san******@***.com";
  String subject="WebDriver - Selenium Testing";
  //Initialising driver
  WebDriver driver = new FirefoxDriver();
  //setting timeout for page load & implicit wait
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
  //Call Url in get method
  //click on Compose button
  //enter TO address & Subject
  //click Send button
  //Logout from Gmail
  driver.findElement(By.xpath("//div[contains(.,'Add account')]//a[contains(text(),'Sign out')]")).click();

Browser methods in WebDriver

WebDriver, The main interface to use for testing, which represents an idealised web browser. The methods in this class fall into three categories:

  1. Control of the browser itself
  2. Selection of WebElements
  3. Debugging aids

Key methods are get(String), which is used to load a new web page, and the various methods similar to findElement(By), which is used to find WebElements. In this post we are going to learn browser controlling methods.


void get(java.lang.String url)

Load a new web page in the current browser window. This is done using an HTTP GET operation, and the method will block until the load is complete. it is best to wait until this timeout is over, since should the underlying page change whilst your test is executing the results of future calls against this interface will be against the freshly loaded page.


//Initialising driver
 WebDriver driver = new FirefoxDriver();
 //setting timeout for page load
 driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
 //Call Url in get method


java.lang.String getCurrentUrl()

Get a string representing the current URL that the browser is looking at. It returns the URL of the page currently loaded in the browser.


//Getting current url loaded in browser & comparing with expected url
 String pageURL = driver.getCurrentUrl();
 Assert.assertEquals(pageURL, "");


java.lang.String getTitle()

It returns the title of the current page, with leading and trailing whitespace stripped, or null if one is not already set.


//Getting current page title loaded in browser & comparing with expected title
 String pageTitle = driver.getTitle();
 Assert.assertEquals(pageTitle, "Google");


java.lang.String getPageSource()

Get the source of the last loaded page. If the page has been modified after loading (for example, by Javascript) there is no guarantee that the returned text is that of the modified page.


//get the current page source
     String pageSource = driver.getPageSource();


void close()

Close the current window, quitting the browser if it's the last window currently open. If there are more than one window opened with that driver instance this method will close the window which is having current focus on it.


//Close the current window


void quit()

Quits this driver, closing every associated window. After calling this method we can not use any other method using same driver instance.


//Quit the current driver session / close all windows associated with driver

These are all very useful methods available in Selenium 2.0 to control browser as required. 

Saturday, October 31, 2015

Program to remove duplicate numbers

Write a program to remove duplicate numbers from given array.

public class RemoveDuplicateNumbers {

  public static void main(String a[]){
         int[] input1 = {2,3,6,6,8,9,10,10,10,12,12};
         int[] output = removeDuplicates(input1);
         for(int i:output){
             System.out.print(i+" ");

 private static int[] removeDuplicates(int[] input) {
   int j = 0;
         int i = 1;
         //return if the array length is less than 2
         if(input.length < 2){
             return input;
         while(i < input.length){
             if(input[i] == input[j]){
                 input[++j] = input[i++];
         int[] op = new int[j+1];
         for(int k=0; k<op.length; k++){
             op[k] = input[k];
         return op;

Write a program to remove duplicate characters from array

public class RemoveDuplicateChars {

 public static void main(String[] args) {
  char c[]={'a','b','g','c','d','e','a','f','c','g'};
  RemoveDuplicateChars obj = new RemoveDuplicateChars();

 public void method1(char a[]) {
  String s=new String(a);
  String temp="";
  for(int i=0;i<s.length();i++) {
   String s1=s.substring(i, i+1);
   if(temp.contains(s1)) {
   } else {

Checking text on web page using WebDriver

While testing any web application, we need to make sure that it is displaying correct text under given elements. Selenium WebDriver provides a method to achieve this. We can retrieve the text from any WebElement using getText() method.

Lets create a test that check for the proper text in flipkart menu tab.

public void testFlipkartMenuText() {
    //Get Text from first item and store it in String variable
    String electronics = driver.findElement(By.cssSelector("li[data-key='electronics']>a>span")).getText();

    //Compare actual & required texts

The WebElement class' getText() method returns value of the innerText attribute
of the element.

P.S : Given script may not work on flipkart site. I've written this code just to give some basic idea of using getText() method.

Locating elements using findElements methods

Selenium WebDriver provides the findElements() method, which returns List of WebElements with matching criteria. This method is useful when we want to do some operation with each element with same locator.


  • Get all links on a page
  • Get all buttons on page
  • Get all options from dropdown
  • Get all rows in table and td s from tr 

Let's create a test to check no of rows in given table.
public void testFindElements() {
  //Get all the tr from table
  List allTrs = driver.findElements(By.cssSelector("table[id='myContacts'] tr"));

  //verify there are 3 trs under given table

  //Iterate all tr tags and print no of td tags in each tr tag
  for(WebElement eachTr : allTrs) {