Tuesday, 28 October 2014

How to handle google auto capture


 import java.util.List;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class GoogleAutoCap {  
  public static void main(String[] args) throws InterruptedException {  
  // TODO Auto-generated method stub  
  WebDriver driver = new FirefoxDriver();  
  driver.get("http://www.google.com");  
  driver.findElement(By.id("gbqfq")).sendKeys("selenium");  // Entering values into the search box
  Thread.sleep(2000);  
  List<WebElement> rows = driver.findElements(By.xpath("//*[@class='gssb_m']"));  // Finding all elements under tag td for auto suggestions
  for (int i=0;i<rows.size();i++)  
  {  
   List<WebElement> cols = rows.get(i).findElements(By.tagName("span")); // span tag contains the result   
   System.out.println(cols.size());  
   for (int j=0;j<cols.size();j++)  
   {  
   System.out.println(cols.get(j).getText()); // printing them one by one 
   }  
  }  
  }  
 }  

Tuesday, 21 October 2014

How to work with similar elements on the page

There are many instances when a developer re-uses a code in  a webpage. For example "OK" button for a prompt. Instead of scripting it again and again, developers prefer re-using a code which results in presence of similar elements on the page .

By similar elements I mean - Elements with same ID and properties;
for example
<span id="OkButton" type="button" value="OK"/>

Let's assume you have 4 copies of the above mentioned element on the page and you want to work with the third element on the same page .

NOTE- Elements appear on a page in order of Top to Bottom . So the third element means from top to bottom i.e third time we spot the same element.

To solve our problem xpath comes in handy for us

First Element
//span[@id='OkButton'] -- will give you first element from top

Second Element
//span[@id='OkButton']//following::span[@id='OkButton'] -- will give you second element on page from top

Third Element
//span[@id='OkButton']//following::span[@id='OkButton']//following::span[@id='OkButton'] -- thrid element

Fourth Element
//span[@id='OkButton']//following::span[@id='OkButton']//following::span[@id='OkButton']//following::span[@id='OkButton'] -- fourth element


NOTE- Some people suggest indexing here i.e. //span[@id='OkButton'][3] -- to move the third element -- This works only in the case when all the similar elements are present just below each other 

<span id="OkButton" type="button" value="OK"/>
<span id="OkButton" type="button" value="OK"/>
<span id="OkButton" type="button" value="OK"/>
<span id="OkButton" type="button" value="OK"/>

And this situation is very rare . As if we consider our example then every OK button will be placed under its specific set of code . 

Wednesday, 1 October 2014

How to Diagnose Element not present on page

The most common error faced by  beginners is "Element not found" . There are multiple reasons for this error to occur, so there are multiple solutions for the problem. Below are some of the common diagnosing techniques I learned with time and would like to share with you people. These techniques could be helpful or may be not, depending on your problem.

" You have used the correct id/xpath and when you inspect the element, Its visible. But , on runtime you are facing the error. "

Solutions - Check that your id/xpath should not result in 2 elements while inspecting element. Normally, what happens that developer re-uses the same code for some elements if the functionality is repeated . This results in duplicate value in a page. So, Inspecting element may highlight the element you want  but  in code that element falls under different category and will result in error. Move to the duplicate element using indexing or following commands and see if it helps you.

 - Use .isDisplayed() and .isEnabled() methods on the element. This will result in true or false. If one them results in false then you have to diagnose ahead. Sometimes, the element is present while inspecting, in the code as well but not visible on the screen. In those cases .isDisplayed() results false. Scroll your page and make the element visible on page and then try working on it. If .isEnabled is false then the element is hidden. You have to first diagnose that how and why this happens, Contact your developer in this case and ask him to correct if its a problem in his code.

- Add some wait before accessing the element. This scenario is usually for the ajax elements. The elements may vary on loading time according to your connection and will result in error. Use Explicit wait or normal Thread.sleep();

- Element is visible on the screen but present under the Iframe and not inspectable. Iframes are concept of page under a page, They are the part of the main code but to access element present inside iframe needs switching to an iframe. Switch and use id/xpath to inspect the element.


Post comments below if these solutions helped you in some way or even solved your problem. If not, lets try working together to find a solution :) 

Monday, 22 September 2014

How to add jar files in eclipse ?

Most of the beginners face the issue of adding jar/libraries to existing project or a new project.
Below are some basic steps with snapshots which will explain the rest of the steps.

1) Right click on the project name.


































2) Either click on "Properties" or "BuildPath". I clicked on Properties.





3) Click on Java Build Path as mentioned in the above snapshot. Click on Add External jars after that.























4) Select the jar file and click on open button .























5) The selected jar is added and shown in the row . Click on OK button to save the result.



Sunday, 21 September 2014

Reading data from excel using Apache POI

Below are the two methods which are used to read data from excel file and write data back to excel file.
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.util.Iterator;  
 import java.util.List;  
 import java.util.Set;  
 import org.apache.poi.hssf.usermodel.HSSFCell;  
 import org.apache.poi.hssf.usermodel.HSSFRow;  
 import org.apache.poi.hssf.usermodel.HSSFSheet;  
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;  
 import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;  
 import org.apache.poi.ss.usermodel.WorkbookFactory;  
 import org.eclipse.jdt.internal.compiler.lookup.UpdatedMethodBinding;  
 // Reading data from excel  
 public static void excelRead(String sPath,String sheetName) throws IOException //sPath-- path where excel is placed , sheetName--The sheet which you want to read  
      {  
           File xlFile= new File(sPath);  
           FileInputStream fin = new FileInputStream(xlFile);  
           HSSFWorkbook wBook= new HSSFWorkbook(fin);  
           HSSFSheet sheetObj=wBook.getSheet(sheetName);  
           MissingCellPolicy mcpObj= HSSFRow.CREATE_NULL_AS_BLANK; //Missing Cell Policy  
           HSSFRow rowObj;  
           HSSFCell cellObj;  
            xRows= sheetObj.getLastRowNum()+1;  
            xCols= sheetObj.getRow(0).getLastCellNum();  
            xData= new String[xRows][xCols];  
           System.out.println("No of rows are "+xRows +" No of Cols are "+xCols);  
           for (int i=0;i<xRows;i++)  
           {  
                //System.out.println("inside loop");  
                rowObj=sheetObj.getRow(i);  
                     for (int j=0;j<xCols;j++)  
                     {  
                          cellObj=rowObj.getCell(j, mcpObj);  
                           String Value=cellToString(cellObj);  
                          //System.out.print(Value+"@@@@");  
                          xData[i][j]=Value;  
                     }  
                //System.out.println("----------------------------------------------------------------");  
           }  
      }  
      public static String cellToString(HSSFCell cell)  
      {  
           int type=cell.getCellType();  
           Object result;  
           switch(type)  
           {  
                case HSSFCell.CELL_TYPE_NUMERIC ://0  
                     //result=cell.getNumericCellValue();-----original  
                     cell.setCellType(HSSFCell.CELL_TYPE_STRING);  
                     result=cell.getStringCellValue();  
                     break;  
                case HSSFCell.CELL_TYPE_STRING: //1  
                     result=cell.getStringCellValue();  
                     break;  
                case HSSFCell.CELL_TYPE_FORMULA: //2  
                     throw new RuntimeException("We can't evluate Formula in java");  
                case HSSFCell.CELL_TYPE_BLANK: //3  
                     result="";  
                     break;  
                case HSSFCell.CELL_TYPE_BOOLEAN: //4  
                     result=cell.getBooleanCellValue();  
                     break;  
                case HSSFCell.CELL_TYPE_ERROR: //4  
                     throw new RuntimeException("This cell has an error");  
                default:  
                     throw new RuntimeException("We had not yet handled this type "+type);  
           }  
           return result.toString().trim();  
           }  
 // Write data back to excel  
      public static void excelWrite(String sPath , String SheetName,String xlData[][] ,int xRows,int xCols) throws IOException  
      {  
           System.out.println("in write Excel");  
           File outXlFile= new File(sPath);  
           HSSFSheet outSheet=null;  
                HSSFWorkbook outBook= null;  
                 if (outXlFile.exists()) {  
                    try {  
                      outBook = (HSSFWorkbook)WorkbookFactory.create(outXlFile);  // If the sheet already exists then this method re-writes the sheet
                    } catch (InvalidFormatException e) {  
                      e.printStackTrace();  
                    }  
                    outSheet = outBook.createSheet(SheetName);  
                  }  
                  else{  
                    outBook = new HSSFWorkbook();  
                    outSheet = outBook.createSheet(SheetName);  
                  }  
                //HSSFSheet outSheet= outBook.createSheet(SheetName);  
                System.out.println("Rows "+xRows+" Cols "+xCols);  
                for (int i=0;i<xRows;i++)  
                {  
                     HSSFRow outRow= outSheet.createRow(i);  
                     for(int j=0;j<xCols;j++)  
                     {  
                          HSSFCell outCell= outRow.createCell(j);  
                          outCell.setCellType(outCell.CELL_TYPE_STRING);  
                          outCell.setCellValue(xlData[i][j]);  
                     }  
                }  
                FileOutputStream fout=new FileOutputStream(outXlFile);  
                outBook.write(fout);  
                fout.flush();  
                fout.close();  
                outBook=new HSSFWorkbook(new FileInputStream(sPath));  
      }  

Wednesday, 17 September 2014

Missing Cell Policy -- Why and how to use it ?


When we read data from excel file using selenium code, most of the people face null
pointers exception if they leave any field blank or null accidentally.
Beginners are the one who face this problem frequently . To avoid this
problem Apache POI comes up with a solution i.e. Missing cell policy.
You can apply this policy on row object . There are 3 basic policies 

CREATE_NULL_AS_BLANK
RETURN_NULL_AND_BLANK
RETURN_BLANK_AS_NULL
You can choose the appropriate policy as suited to your demands.
Below is the code that shows implementation of the same :-
This code is to read data from an excel file and store the input in 2 dimensional arrays.

 
public static void excelRead(String sPath,String sheetName) throws IOException //spath -- Path to excel file , sheetName-- The sheet you want to read  
      {  
           System.out.println("In excelRead method");  
           File xlFile= new File(sPath);  
           FileInputStream fin = new FileInputStream(xlFile);  
           HSSFWorkbook wBook= new HSSFWorkbook(fin);  
           HSSFSheet sheetObj=wBook.getSheet(sheetName);  
           MissingCellPolicy mcpObj= HSSFRow.CREATE_NULL_AS_BLANK; //Missing cell policy applied here  
           HSSFRow rowObj;  
           HSSFCell cellObj;  
            xRows= sheetObj.getLastRowNum()+1;  
            xCols= sheetObj.getRow(0).getLastCellNum();  
            xData= new String[xRows][xCols]; // two dimensional array  
           System.out.println("No of rows are "+xRows +" No of Cols are "+xCols);  
           for (int i=0;i<xRows;i++)  
           {  
                //System.out.println("inside loop");  
                rowObj=sheetObj.getRow(i);  
                     for (int j=0;j<xCols;j++)  
                     {  
                          cellObj=rowObj.getCell(j, mcpObj);// policy object applied here   
                           String Value=(cellObj.getStringCellValue());  
                          xData[i][j]=Value;  
                     }  
           }