Earn Money in 10 days

Selenium Videos

Protractor In Selenium

Livechat

Wednesday, 29 October 2014

What is xpath.

  • In automation we need to perform some operations on Webelement.
  • For any website application there are some common pages on which you found button,textbox,radiobutton,dropdown button etc.
  • For performing the action the first thing you need to find the xpath for it.
What is xpath?

In every web-based applications the XPaths or locators are unique addresses for each and every web object. It can be used with selenium to
perform operations on each object present in the webpage. In the web page each web-object has a primary unique XPath.
Xpath detailed explations.The use of xpath.
  • Selenium actully uses xpath to identify elements.
  • Webpage has varies of object(eg:images,textboxes,textfields,buttons,radiobutton,checkboxes etc.)
  • Each and every object has a unique id/name/path called xpath.
  • If developer change the color of button in a webpage later but xpath remain same.
  • If you are willing to become an automation tester in IT industry,Learning xpath is makes the thing easy.
  • When automate a website,have to identify the object of the page and every webpage according to testcase.

How to Find xpath

How we get xpath for Mozilla Firefox
If  your webpage is running of firefox browser it is very easy to get xpath very easily.You just need to install two addons on Mozilla(Firebug and FirePath)
1.Download Firebug
 But before inspecting  you need to download Firepath tool.
2.Download Firepath
After installing FirePath you can start finding xpath of any webelement.

Step7:Now press F12 for finding any webelement in firefox.
There are two type of xpath.
1.Absolute xpath
2.Relative xpath
Absolute path will start with root path (/) and Relative path will from current path (//)
Absolute xpath
Let me take an example of https://www.facebook.com/
Go to https://www.facebook.com/
Now press F12 or fn+F12
                                                     Tool inspector for Finding xpath


Absolute xpath:

If you need to find out Absolute xpath select this General absolute xpath.It will give you absolute xpth.


Absolute xpath of email Textbox.

 Relative xpath:

If you need to find out relative xpath then uncheck the Generate absolute xpath.


Absolute xpath of email textbox.

Difference Between Absolute and Relative xpath:

Absolute xpath sometime fails because sometime developer change the div.So if you will use absolute xpath technically it work but if any node change then xpath will not work.
So you need to find out Relative xpath.

Differences in Absolute and Relative xpath

Absolute XPath starts with the root node or a forward slash (/).
Advantage
 It identifies the element very fast.
Disadvantage
 If any other tag added in between, then this path will no longer works.
Suppose Absolute xpath is
html/body/div[1]/div[1]/div/div/div/div/div/div/form/table/tbody/tr[2]/td[1]/input

If any of the div add in this xpath then this xpath will fail.
html/body/div[1]/div[1]/div/div/div/div/div2/div/div/form/table/tbody/tr[2]/td[1]/input
Relative xpath
1 Starts with //
2.//input” matches all the paragraph elements starts with input
3. //input[@id='email'] is a relative xpath.
Some basic concept you should all know.
Go to this link

Click on inspector and take the curser to your username.This will give you an xpath.

Note:This firebug always give you an xpath which is xpath by id.

But in selenium sometimes id may change so you have to take a different attributes.
How to write xpath mannually.

Syntax for path
//*[@attribute='value']
//is used to find relative element
* is used for tagname..Tagname is always input for textbox,radiobutton,button.

Tagname is always available for any element.
Tagname is always written with this < bracket Example <input,<p<li
Input,p,li are the tag name.
xpath for username
<input id="username" type="text" maxlength="40" value="" name="username">
input is tag name
Attributes are id,type,maxlength,name
values are username,text,40,username.Values are written in orange color.
//*[@attribute='value']

You can write xpath as:
Your first prefernce should be find id of that element
//input[@id='username']

After that you can use any attribute
Xpath by name
//input[@name='username']
Sometime attributes are same so you all need to find out unique element for object.

Thursday, 16 October 2014

How to Read Excel sheet.

For reading excel files

We used Apache poi jar files.

We just need 5 jar files for reading excel files in selenium.
dom4j
xmlbeans-2.3.0.jar
poi-3.6
poi-ooxml-3.6
poi-ooxml-schemes.
Step1:Download the Poi jar files .Click here
For reference.
If you want to search more you can also download  POI apache jar files from here.
Now Go to Eclipse>Create a project>ReadingExcelsheet

Step2:1.Add these poi jar files into the project.

2.Add selenium jar files into project.
For reference click here.
3.Use this code for reading excel file.In this code i have written all the methods which we can use for reading excel file.

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFHyperlink;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.*;


import java.io.*;
import java.util.Calendar;


public class Xls_Reader {
public static String filename = System.getProperty("user.dir")+"\\src\\config\\testcases\\TestData.xlsx";
public  String path;
public  FileInputStream fis = null;
public  FileOutputStream fileOut =null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row   =null;
private XSSFCell cell = null;

public Xls_Reader(String path) {

this.path=path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
// returns the row count in a sheet
public int getRowCount(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return 0;
else{
sheet = workbook.getSheetAt(index);
int number=sheet.getLastRowNum()+1;
return number;
}

}

// returns the data from a cell
public String getCellData(String sheetName,String colName,int rowNum){
try{
if(rowNum <=0)
return "";

int index = workbook.getSheetIndex(sheetName);
int col_Num=-1;
if(index==-1)
return "";

sheet = workbook.getSheetAt(index);
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_Num=i;
}
if(col_Num==-1)
return "";

sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(col_Num);

if(cell==null)
return "";
//System.out.println(cell.getCellType());
if(cell.getCellType()==Cell.CELL_TYPE_STRING)
 return cell.getStringCellValue();
else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA ){

 String cellText  = String.valueOf(cell.getNumericCellValue());
 if (HSSFDateUtil.isCellDateFormatted(cell)) {
          // format in form of M/D/YY
 double d = cell.getNumericCellValue();

 Calendar cal =Calendar.getInstance();
 cal.setTime(HSSFDateUtil.getJavaDate(d));
           cellText =
            (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
          cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" +
                     cal.get(Calendar.MONTH)+1 + "/" +
                     cellText;
       
          //System.out.println(cellText);

        }



 return cellText;
 }else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
     return "";
 else
 return String.valueOf(cell.getBooleanCellValue());

}
catch(Exception e){

e.printStackTrace();
return "row "+rowNum+" or column "+colName +" does not exist in xls";
}
}

// returns the data from a cell
public String getCellData(String sheetName,int colNum,int rowNum){
try{
if(rowNum <=0)
return "";

int index = workbook.getSheetIndex(sheetName);

if(index==-1)
return "";


sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum-1);
if(row==null)
return "";
cell = row.getCell(colNum);
if(cell==null)
return "";

 if(cell.getCellType()==Cell.CELL_TYPE_STRING)
 return cell.getStringCellValue();
 else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA ){

 String cellText  = String.valueOf(cell.getNumericCellValue());
/* if (HSSFDateUtil.isCellDateFormatted(cell)) {
          // format in form of M/D/YY
 double d = cell.getNumericCellValue();

 Calendar cal =Calendar.getInstance();
 cal.setTime(HSSFDateUtil.getJavaDate(d));
           cellText =
            (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
          cellText = cal.get(Calendar.MONTH)+1 + "/" +
                     cal.get(Calendar.DAY_OF_MONTH) + "/" +
                     cellText;
       
         // System.out.println(cellText);

        }

 */

 return cellText;
 }else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
     return "";
 else
 return String.valueOf(cell.getBooleanCellValue());
}
catch(Exception e){

e.printStackTrace();
return "row "+rowNum+" or column "+colNum +" does not exist  in xls";
}
}

// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String data){
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);

if(rowNum<=0)
return false;

int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;


sheet = workbook.getSheetAt(index);


row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equals(colName))
colNum=i;
}
if(colNum==-1)
return false;

sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);

cell = row.getCell(colNum);
if (cell == null)
       cell = row.createCell(colNum);

   // cell style
   CellStyle cs = workbook.createCellStyle();
   cs.setWrapText(true);
   cell.setCellStyle(cs);
   cell.setCellValue(data);

   fileOut = new FileOutputStream(path);

workbook.write(fileOut);

   fileOut.close();

}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}


// returns true if data is set successfully else false
public boolean setCellData(String sheetName,String colName,int rowNum, String data,String url){
//System.out.println("setCellData setCellData******************");
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);

if(rowNum<=0)
return false;

int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;


sheet = workbook.getSheetAt(index);
//System.out.println("A");
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
//System.out.println(row.getCell(i).getStringCellValue().trim());
if(row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))
colNum=i;
}

if(colNum==-1)
return false;
sheet.autoSizeColumn(colNum); //ashish
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);

cell = row.getCell(colNum);
if (cell == null)
       cell = row.createCell(colNum);

   cell.setCellValue(data);
   XSSFCreationHelper createHelper = workbook.getCreationHelper();

   //cell style for hyperlinks
   //by default hypelrinks are blue and underlined
   CellStyle hlink_style = workbook.createCellStyle();
   XSSFFont hlink_font = workbook.createFont();
   hlink_font.setUnderline(XSSFFont.U_SINGLE);
   hlink_font.setColor(IndexedColors.BLUE.getIndex());
   hlink_style.setFont(hlink_font);
   //hlink_style.setWrapText(true);

   XSSFHyperlink link = createHelper.createHyperlink(XSSFHyperlink.LINK_FILE);
   link.setAddress(url);
   cell.setHyperlink(link);
   cell.setCellStyle(hlink_style);
   
   fileOut = new FileOutputStream(path);
workbook.write(fileOut);

   fileOut.close();

}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}



// returns true if sheet is created successfully else false
public boolean addSheet(String  sheetname){

FileOutputStream fileOut;
try {
workbook.createSheet(sheetname);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
    fileOut.close();  
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

// returns true if sheet is removed successfully else false if sheet does not exist
public boolean removeSheet(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;

FileOutputStream fileOut;
try {
workbook.removeSheetAt(index);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
   fileOut.close();  
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if column is created successfully
public boolean addColumn(String sheetName,String colName){
//System.out.println("**************addColumn*********************");

try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
int index = workbook.getSheetIndex(sheetName);
if(index==-1)
return false;

XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

sheet=workbook.getSheetAt(index);

row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);

//cell = row.getCell();
//if (cell == null)
//System.out.println(row.getLastCellNum());
if(row.getLastCellNum() == -1)
cell = row.createCell(0);
else
cell = row.createCell(row.getLastCellNum());
     
       cell.setCellValue(colName);
       cell.setCellStyle(style);
     
       fileOut = new FileOutputStream(path);
workbook.write(fileOut);
   fileOut.close();  

}catch(Exception e){
e.printStackTrace();
return false;
}

return true;


}
// removes a column and all the contents
public boolean removeColumn(String sheetName, int colNum) {
try{
if(!isSheetExist(sheetName))
return false;
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet=workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
style.setFillPattern(HSSFCellStyle.NO_FILL);

 

for(int i =0;i<getRowCount(sheetName);i++){
row=sheet.getRow(i);
if(row!=null){
cell=row.getCell(colNum);
if(cell!=null){
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
   fileOut.close();
}
catch(Exception e){
e.printStackTrace();
return false;
}
return true;

}
  // find whether sheets exists
public boolean isSheetExist(String sheetName){
int index = workbook.getSheetIndex(sheetName);
if(index==-1){
index=workbook.getSheetIndex(sheetName.toUpperCase());
if(index==-1)
return false;
else
return true;
}
else
return true;
}

// returns number of columns in a sheet
public int getColumnCount(String sheetName){
// check if sheet exists
if(!isSheetExist(sheetName))
return -1;

sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);

if(row==null)
return -1;

return row.getLastCellNum();



}
//String sheetName, String testCaseName,String keyword ,String URL,String message
public boolean addHyperLink(String sheetName,String screenShotColName,String testCaseName,int index,String url,String message){
//System.out.println("ADDING addHyperLink******************");

url=url.replace('\\', '/');
if(!isSheetExist(sheetName))
return false;

   sheet = workbook.getSheet(sheetName);
 
   for(int i=2;i<=getRowCount(sheetName);i++){
    if(getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)){
    //System.out.println("**caught "+(i+index));
    setCellData(sheetName, screenShotColName, i+index, message,url);
    break;
    }
   }


return true;
}
public int getCellRowNum(String sheetName,String colName,String cellValue){

for(int i=2;i<=getRowCount(sheetName);i++){
    if(getCellData(sheetName,colName , i).equalsIgnoreCase(cellValue)){
    return i;
    }
   }
return -1;

}

// to run this on stand alone
public static void main(String arg[]) throws IOException{

//System.out.println(filename);
Xls_Reader datatable = null;


datatable = new Xls_Reader("C:\\riti\\Fr_Wles\\data.xlsx");
for(int col=0 ;col< datatable.getColumnCount("TC"); col++){
System.out.println(datatable.getCellData("TC", col, 1));
}
}


}
Excel sheet you can download from here

How to read this excel sheet data in selenium.
1.How to count total number of rows from excel sheet.
2.How to get data from Excelsheet.

Writing in excel sheet.
3How to set data in excel sheet 

public class ReadingExcelsheet {

public static void main(String[] args) {
//Make an object of Xls_Reader 
//In this xls reader construction add the path of your excel sheet
Xls_Reader datatable = new Xls_Reader("C:\\Users\\Ritika Gulati\\Documents\\Datatest.xlsx");
//How to count total number of rows in excel sheet
// datatable.getRowCount(sheetName)
int rowdata = datatable.getRowCount("Records");
System.out.println("Total Rows in excel sheet           "+rowdata);
//How to get the data from excelsheet
// datatable.getCellData(sheetName, colNum, rowNum)
String data= datatable.getCellData("Records", "City", 3);
System.out.println("This is data from 3rd row ,colomn name is city and sheet name records       "+data);
String data2= datatable.getCellData("Records", "City", 2);
System.out.println("data from 2nd row,colomn name is city and sheet name records "+data2);
How to set data in excel sheet
//datatable.setCellData(sheetName, colName, rowNum, data2)
datatable.setCellData("Records", "City", 10, "new data entered ");

}

}

Wednesday, 15 October 2014

Selenium First Script

Prerequisites for learning WebDriver

Basic Core Java

How to start work with WebDriver/Selenium First Script

Three simple Steps for writing First script

1.Download Jar files for Selenium 

2.After that configure Jar files in Eclipse.

3.Click on Eclipse.





4.Choose Your WorkSpace.Click on ok.

6.You will get this screen.
7.Go to File>JavaPrject


  7.Type name for the project.Project name should be meaningfull.Click on Finish.
 
8.Click on traingle>Select Src>Right click
9.Select Package and type/Enter name for package.


10.Package name should be in small letter.

11.Now select Package>Click on class

12.Type name and Click Finish.

 
 13.Right Click on project>Go to Properties>Select Java Build Path


14.Click on Add External Jar>Give path of your Selenium Jar Files>Add these JarFiles.Add all the Jar files which are in lib Folder.Click on Ok.Now Selenium Jar is configured. 15.Now click on class And start Write Script into that class

16.Now click on WebDriver written in script and  and import the class of WebDriver and Import Firefox Driver.
17.After importing you will get this screen.Now you can start working with Webdriver methods.Here driver is an refernce of WebDrive.Here we are opening the FirefoxDriver.
19.Now driver.get method will launch the url(url which you will enter) For opening the url we will always use driver.get(urlname).

Tuesday, 14 October 2014

How to Download Selenium Jar Files.

Step:1 Download jar files from here.

Step2:Click on Download  

This zip folder will be download after clicking on that download button.

Right click >Select WinRar>Select Extract Here

After Extracting you will get jar file of Selenium..

Sunday, 12 October 2014

How to download Eclipse

                                              Step 1:Click here

Step2:Click on Windows 32 Bit or Window 64 Bit depends on your system configuration.

Step3:Start download.Eclispe takes sometime to download.If your internet speed is good then it will download faster.


Step4:After downloading successfully you will get a Zip folder like this.

Step5:Now Extract...
Step6:After Extracting you will get a folder like this.

Step7:After clickng on that you will get Eclipse.Now click on it.
Step8:Click on eclipse.
Step9:Choose your WorkSpace and click ok.

Step10:Start working with eclipse

Step11:Create your projects in eclipse.


Popular Posts

 
subscribe
Subscribe Us
emailSubscribe to our mailing list to get the updates to your email inbox... We can't wait more to have your email in our subscribers email list. Just put your nice email in below box: