QaMantra: January 2018

Locators in Selenium

Locators 

Locators provide a mechanism to access the HTML elements on a web page. Once we locate an element/object on any web page, Then to get or store the Webelement we use findElement() or Findelements()  method to find or strore the located webelement or List of elements then we can write test cases to execute on them.
                                               
                                              OR

Selenium uses what is called locators to find and match the elements of your page that it needs to interact with


                           For example, If we would like click on any button then locators will help me to click on button , We will see that in details in the subsequent sections of this tutorial.


Types of Locators in Selenium 

Selenium webdriver Have 8 locators to find the Web elements on web page , We have mentioned the list of locators as per priority to be used while Coding.


  • ID
  • Name 
  • Link Text
  • Partial Link Text
  • Tag Name 
  • Class Name
  • Css Selector
  • XPATH   - Absolute and Relative 

Locators




Configuration of Selenium WebDriver Project With Java part 2

In Last Article we have seen that what different stuff required for Maven Project and Java Project Configuration  ,In this article we will learn about final configuration of Selenium WebDriver Project


  • Create a Java Project or Maven Project if You want to work on Existing Project then Skip this Step ,otherwise i prefer to create Setup in New Project ,if You do not How To create Simple Java Project Click Here
  • Right click on  Java/Maven Project  >New >Folder > Enter Folder Name Like -'Jar' >Click on Finish
  • For Java Project -Copy Selenium Standalone jar which you have downloaded in First step and Paste Inside Folder 'Jar'  > Right Click on Selenium Standalone jar >Go To Build Path > Click On Add To Build Path ,Maven Project user should skip this Step 
  • For Maven Project Copy Dependency from Previous Article and Paste inside POM.XML Dependencies Tag 
  • Right click on  Java/Maven Project  >New >Folder > Enter Folder Name Like -'Exe' >Click on Finish
  • Copy ChromeDriver.exe File which you have downloaded in First step and Paste Inside Folder 'Exe' for Chrome Browser ,you can use GeckoDriver for Firefox ,IEDriver for Internet Explore and So on 
                          Now your Selenium Configuration beginners phase have been completed now you can Start to Automate to any Web Application .

 Previous Article                                                                                                       Continue Reading ...

Configuration of Selenium WebDriver Project With Java part 1

To install Selenium means to set up a project in a development so you can write a program using Selenium. How you do this depends on your programming language and your development environment and Selenium is Language Independent Tool So You can use any one Programming Language among -  Java , C# , Python , Ruby , PHP , JavaScript , Perl .


Java 
The easiest way to set up a Selenium 2.0 Java project is to use Maven. Maven will download the java bindings (the Selenium 2.0 java client library) and all its dependencies, and will create the project for you, using a maven pom.xml (project configuration) file. Once you’ve done this, you can import the maven project into your preferred IDE, IntelliJ IDEA or Eclipse.
  
Maven Project
          
 For Maven Project you Should have Selenium Dependency in POM.xml ,Selenium Dependency you can get from Here .

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.8.1</version>
</dependency>
Copy this Dependency and Paste inside a  <Dependencies>  Paste Selenium Dependency  </Dependencies> Tag 
                  Be sure you specify the most current version. At the time of writing, the version listed above was the most current, however there were frequent releases immediately after the release of Selenium 2.0. Check the Maven download page for the current release and edit the above dependency accordingly.

Now, from a command-line, CD into the project directory and run maven as follows.

mvn clean install
     Java Project  

For those user who is using Simple Java Project they can Download Jar Selenium Latest Jar

Previous Article                                                                                                       Continue Reading ...

Introducing Selenium WebDriver

The primary new feature in Selenium Webdriver 2.0 is the integration of the WebDriver API. WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API. Selenium-WebDriver was developed to better support dynamic web pages where elements of a page may change without the page itself being reloaded. WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems.



WebDriver Compared to Selenium-RC

Selenium-WebDriver makes direct calls to the browser using each browser’s native support for automation. How these direct calls are made, and the features they support depends on the browser you are using. Information on each ‘browser driver’ is provided later in this chapter.

For those familiar with Selenium-RC, this is quite different from what you are used to. Selenium-RC worked the same way for each supported browser. It ‘injected’ javascript functions into the browser when the browser was loaded and then used its javascript to drive the AUT within the browser. WebDriver does not use this technique. Again, it drives the browser directly using the browser’s built in support for automation.

Previous Article                                                                                                        Continue Reading ...


WebDriver and the Selenium-Server

You may, or may not, need the Selenium Server, depending on how you intend to use Selenium-WebDriver. If your browser and tests will all run on the same machine, and your tests only use the WebDriver API, then you do not need to run the Selenium-Server; WebDriver will run the browser directly.



There are some reasons though to use the Selenium-Server with Selenium-WebDriver.


  • You are using Selenium-Grid to distribute your tests over multiple machines or virtual machines (VMs).
  • You want to connect to a remote machine that has a particular browser version that is not on your current machine.
  • You are not using the Java bindings (i.e. Python, C#, or Ruby) and would like to use HtmlUnit Driver

Why we assign Browser instance to webdriver interface

WebDriver driver = new FirefoxDriver();

WebDriver driver = new ChromeDriver();

WebDriver driver = new IEDriver();


In the above statement, WebDriver is an interface. An interface contains empty functions that have been defined but not implemented. These functions can be implemented by anyone as long as the method type and signatures can not be violated.

                             Therefore, an interface is also known as contract, because you can use an interface as you like but you cannot change the way it has been defined. And, since it has empty methods you won't actually need to instantiate it and so you cannot instantiate it.

FirefoxDriver/ChromeDriver/IEDriver and so on browser Driver is a class that has been written specifically for the Firefox/Chrome/IE and many browser. It has methods that are implemented and it can be instantiated. It can perform all functions (or methods) on the Firefox browser as defined in the interface WebDriver.


WebDriver API Architecture


So in the above statement, we are actually telling FirefoxDriver/ChromeDriver/IEDriver class that " you can automate the various methods that you want on the Firefox/Chrome/IE browser but you need to stick to the contract defined in WebDriver".

                                   So we declare a reference variable of type WebDriver and then use it to instantiate FirefoxDriver/ChromeDriver/IEDriver, which means that the object (driver) is of type WebDriver but points to the memory allocation to all data and methods in FirefoxDriver/ChromeDriver/IEDriver (and, as mentioned above, the FirefoxDriver/ChromeDriver/IEDriver class already has the implemented version of methods in WebDriver)

Continue Reading

How to Switch window in Selenium

Few Web application may have multiple windows,Tab & frames. While Navigating to Multiple window’s in selenium webdriver assigns an alphanumeric id to each window as soon as
the WebDriver object is instantiated ,id called as a window’s handler means each unique window has a unique ID, so that Selenium can able to differentiate while switching onee window to another .

                       Once the user switch to new(child) window driver control will also switch to new(child) window and he would not able to perform any operation on parent window until unless switch to parent window.


GetWindowHandle 

To Handle the current one window only

Syntax 


//Return a string of alphanumeric window handle                                           String  handle= driver.getWindowHandle();

Switch Current Window

From Above Mentioned Syntax we will get Current one Window Handler and based on that one Handler Script will switch window .


Syntax 

 driver.switchTo().window(handle);

GetWindowHandles 

To Handle the current All windows

Syntax 


//Return a set of All window handle                                                           Set<String>= driver.getWindowHandles();
Switch Current Window

From Above Mentioned Syntax we will get Current Multiple Window Handlers and based on that Handlers Script will switch to required  window . we have multiple window handler so we are going to use iterator ,through iterator we will iterate to each window and get handler id that window & which ever window want to switch use that handler id .

Syntax 

for (String Child_window: driver.getWindowHandles()) {
 
    driver.switchTo().window(Child_window);}
Program

Program is written for Multiple window handling ,In this program Scenario is user land on a web page ,there is a multiple Link and if user will click to any one of link will navigate to new window .



package PackageOne;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class irctcPopUp extends BaseClass {

 @Test

 public void MultipleWindowHandle() throws InterruptedException {

  System.setProperty("webdriver.chrome.driver", ".\\Exe\\chromedriver.exe");
  WebDriver driver = new ChromeDriver();

  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

  // Launch QaMantra Web Page
  driver.get("https://www.Qamantra.com/");

  Thread.sleep(5000);
// Application Specific , not required for Every Application 
  EnterSubscriberEmail();
  // Navigate to Contact Web Page
  driver.findElement(By.xpath("//a[contains(text(),'Contact')]")).click();
// Application Specific , not required for Every Application
  EnterSubscriberEmail();
  // Click to QaMantraFaebookLink
  driver.findElement(By.xpath("//a[contains(text(),'FacebookQaMantraPage')]")).click();

 // get current window ID called as a parent window
  String Parent_Window = driver.getWindowHandle();

  // Switching from parent window to child window
  for (String Child_Window : driver.getWindowHandles()) {
   
  // switch to new window which is opened after click on //FacebookQaMantraPage Link
 // Now user can perform any operation on new window   
   driver.switchTo().window(Child_Window);
   
   // if user is Already Login to Facebook //Page ,Will Navigate to QaMnatra Page
   // and will hit like button 
   driver.findElement(By.xpath("//a[@data-testid='page_profile_liked_button_test_id']")).click();
   
   //Navigate back to Parent window
   driver.switchTo().window(Parent_Window);
  }

 }
 // to Handle Subsriber Email POPUp on qamantra Page
 // Its Application Specific 
 
 public void EnterSubscriberEmail(){
  driver.findElement(By.xpath("//input[@placeholder='Email address']")).sendKeys("yorEmailID");
  driver.findElement(By.xpath("//span[contains(text(),'Subscribe')]")).click();
 }
}

How to Find broken Links in Selenium

Link 

A link is an HTML object that allows you to jump to a new webpage when you click or tap it. Links means of navigating between pages on the web.

Broken Link 

A broken link is also called a dead link ,broken link or dead link is a link on a web page that no longer works because the website is down or page does not Exist ,When a broken link is clicked, an error message is displayed.


Reason for Broken Links 

  • 404  Page Not Found  : Destination Web Page has been Removed by owner 
  • 400 Bad Request  : The server cannot or will not process the request due to wrong requested url Address .
  • The use has restricted due to some firewall settings, firewall have blocked access to the Destination web Page
  • Misspellings in the link



How To Find Broken Links Through Script in Selenium

Manual checking of All links is a hectic work, because each webpage may have a thousands of links & manual process has to be repeated for all pages, Selenium Script will Automate process of Link Verification .


Step to Boken Link Verification
  • Collect all the links of web page on the basis of tag <a> .
  • Send HTTP request for each link .
  • verify HTTP response code for each link.
  • Find out whether the link is valid or broken based on HTTP response code.
  • It should be repeated for all.
Program

package com.abof.scripts;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;

public class JavaProgram {
 /**
  * 
  * @author QaMantra
  */

 @Test
 public void main() throws InterruptedException {

  System.setProperty("webdriver.chrome.driver", "C:\\Users\\user\\workspace\\Abof\\ExeFile\\chromedriver.exe");
  WebDriver driver = new ChromeDriver();

  driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

  driver.get("https://www.Qamantra.com/");

  Thread.sleep(5000);
// Find Element Based on Tag <a> and Store as List of WebElement  List<WebElement> links = driver.findElements(By.tagName("a"));

System.out.println("Total links are " + links.size());

// used for loop to iterate to each WebElement of Link
  for (int i = 0; i < links.size(); i++) {
   WebElement element = links.get(i);

       // By using "href" attribute, we could get the url of the //requried Link
   
  String url = element.getAttribute("href");

// calling verifyLink() method here.Which is created below
   verifyLink(url);
  }
 }

  // verifyLink(String urlLink)Function verify broken links and //return the server response status.

 public void verifyLink(String urlLink) {
  try {

      // create object of the URL Class and pass the urlLink as //parameter
   URL link = new URL(urlLink);

// Create a connection using URL object (i.e., link)
  HttpURLConnection httpConn = (HttpURLConnection) link.openConnection();

   // Set the timeout for 3 seconds
   httpConn.setConnectTimeout(3000);

   // connect using connect method
   httpConn.connect();

 // use getResponseCode() to get the response code.
   if (httpConn.getResponseCode() == 200) {
System.out.println(urlLink + " - " + httpConn.getResponseMessage());
 System.out.println(httpConn.getResponseMessage());

   } else {
System.out.println(urlLink + " - " + httpConn.getResponseMessage());
System.out.println(httpConn.getResponseMessage());
   }

  }

  catch (Exception e) {
   e.printStackTrace();

  }
 }
}





How to get Numeric Value from AlphaNumeric String in Java

Program with using Regex :

package com.abof.scripts;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaProgram {
 /**
  * 
  * @author   QaMantra
  */
 //Java Program to get Numeric Value from AlphaNumeric Without  //Regex
 public static void main(String[] args) {
  
  String str=" abc d 1234567890pqr 54897";

  Pattern p = Pattern.compile("(\\d+)");
  Matcher m = p.matcher(str);
  while(m.find())
  {
      System.out.println("Numeric Value : "+m.group(1));
  }
}}
output :                                                        Numeric Value : 1234567890
Numeric Value : 54897

Program without using Regex :


package com.abof.scripts;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaProgram {
 /**
  * 
  * @author   QaMantra
  */
 
 //Java Program to get Numeric Value from AlphaNumeric Without Regex
 public static void main(String[] args) {
  String str = "abc d 1234567890pqr 54897";
     StringBuilder myNumbers = new StringBuilder();
     for (int i = 0; i < str.length(); i++) {
         if (Character.isDigit(str.charAt(i))) {
             myNumbers.append(str.charAt(i));
             System.out.println(str.charAt(i) + " is a digit.");
         } else {
             System.out.println(str.charAt(i) + " not a digit.");
         }
     }                                                   System.out.println("Numeric Value : " + myNumbers.toString());
 }}
output :                                                        a not a digit.
b not a digit.
c not a digit.
  not a digit.
d not a digit.
  not a digit.
1 is a digit.
2 is a digit.
3 is a digit.
4 is a digit.
5 is a digit.
6 is a digit.
7 is a digit.
8 is a digit.
9 is a digit.
0 is a digit.
p not a digit.
q not a digit.
r not a digit.
  not a digit.
5 is a digit.
4 is a digit.
8 is a digit.
9 is a digit.
7 is a digit.
Your numbers: 123456789054897

How to remove Duplicate value from Array in Java

package com.abof.scripts;

public class JavaProgram {
 /**
  * 
  * @author   QaMantra
  */
 
 
 // program written for remove duplicate value
 public static void main(String[] args) {
  
  {
       
            int array[] = { 10, 20, 30, 20, 40, 40, 50, 30, 10, 50 };// array of ten    
            // elements
            int size = array.length;
            System.out.println("Size before deletion: " + size);
 
            for (int i = 0; i < size; i++) 
            {
 
                for (int j = i + 1; j < size; j++) 
                {
 
 // To Check i indeex value is equal to j index value or not 
                    if (array[i] == array[j]) 
                    {
                        while (j < (size) - 1) 
                        {
                         // swaping the value
                            array[j] = array[j + 1];
                            j++;
                        }   
                        size--;
                    }
                }
            }
            System.out.println("Size After deletion: " + size);
 
            for (int m = 0; m < size; m++) 
            {
                System.out.println(array[m]); // printing the values
            }
    }
  
  
 }

}
output :                                                        Size before deletion: 10
Size After deletion: 5
10
20
30
40
50

                                       Top Java Program Asked in Selenium Interview Questions and Answers  


How to read data from Excel using Column Name in Java Selenium

Java provides different API to Read and Write a File with help of Selenium. In this Post, we will learn how can we read and write from Excel file by using Java IO package,JXL and Apache POI library.
            If your are using any Automation Framework you must know About Read and Write fro Excel, We have to use This Concept while working in Data Driven Framework .


Step to Read Data from Excel Using Apache POI jar


To Read or Write From Excel,Apache Community provides a very widely used library POI. This library have features to read and write both XLS and XLSX file format of Excel.

HSSF implementation is provided by POI library to read 'XLS' Files and XSSF implementation of POI library to read 'XLSX' File ,Lets go to Deep Die .......


Types of Classes and InterFace in Apache POI 


 

Excel Classes

    

 Read Data from Excel File

  • Go To Java Project 
  • Right Click on Java Project
  • Create a New Folder with Name 'testData'
  • Copy Any Blank Excel File from Your PC and Paste Inside Folder 'testData'
  • Open Excel File 
  • Enter The Excel Sheet Name 'LoginDataSheet'
  • Enter Any Website Login Credential Whom you want To Read
  


Excel File


ExcelName



package com.abof.generic; // As Per you Package Name 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class GetCellValueBasedonColumnName {

 public static String readdatafromExcelusingcolumnName(String ColumnName)
   throws EncryptedDocumentException, InvalidFormatException, IOException {
  String SheetName = "LoginDataSheet";
  File file = new File(".\\testData\\data.xlsx");
  FileInputStream fi = new FileInputStream(file);
  Workbook wb = WorkbookFactory.create(fi);
  Sheet sheet = wb.getSheet(SheetName);
  // it will take value from first row
  Row row = sheet.getRow(0);
// it will give you count of row which is used or filled
  short lastcolumnused = row.getLastCellNum();

  int colnum = 0;
  for (int i = 0; i < lastcolumnused; i++) {
   if (row.getCell(i).getStringCellValue().equalsIgnoreCase(ColumnName)) {
    colnum = i;
    break;
   }
  }

  // it will take value from Second row
  row = sheet.getRow(1);
  Cell column = row.getCell(colnum);
  String CellValue = column.getStringCellValue();

  return CellValue;

 }}
       
//Main method called to ReadExcel Method
 public static void main(String[] args)
   throws EncryptedDocumentException, InvalidFormatException, IOException {
  readdatafromExcelusingcolumnName("UserName");
 
 System.out.println("user Name value is : "+value);
} }
output :  user Name value is : vivekjha.rgec@gmail.com

Please Read Previous Article For More Clarity on Hssf and xssf workbook :








Top 5 Most Popular Java Programs Asked in Selenium Interview in 2018

Que : write a Program for Fibonacci Series in Java


Ans : The Fibonacci Series is a sequence of Integers and In which Next number is sum of Two Previous numbers .

There is Two Methods To Print fibonacci Series 

  • Fibonacci series without recursion
  • Fibonacci series with recursion 


Program :



Type 1 : Fibonacci series program without recursion in Java


public class FibonacciProgramWithoutRecursion{  
public static void main(String[] args) {
      int a1=0,a2=1,a3,i,count=5;    
      System.out.print(a1+" "+a2 );
// 0 and 1 dont have previous number 
   for(i=2;i<count;++i)   
   {    
    a3=a1+a2;    
    System.out.print(" "+a3);    
    a1=a2;    
    a2=a3;    
   }}}  

Type 2 : Fibonacci series program with recursion in Java


public class FibonacciProgramWithRecursion{  
 static int b1=0,b2=1,b3=0;    
 public static void FibonnacciNo(int count){    
    if(count>0){    
         b3 = b1 + b2;    
         b1 = b2;    
         b2 = b3;    
         System.out.print(" "+b3);   
         FibonnacciNo(count-1);    
     }    
 }    
 public static void main(String args[]){    
  int count=5;    
  System.out.print(b1+" "+b2);//printing 0 and 1    
  FibonnacciNo(count-2);//n-2 because 2 numbers are already printed   
 }  
}  

Que : Write a Program for Prime Number in Java ?


Ans   : Prime Number is a number who can divide by 1 or itslef and Prime Number is a number greater than 1 ,Prime No. Likes - 3,5,7,11,13,17,19 and so on , We Should know two importants point regarding prime no is :

Note1 - 0 and 1 is not a prime number 

Note2 - Only 2 is Even Prime Number rest of All Even no can devide by 2 or other numbers

Program :

// we are going to write a program to check that 7 is prime no or not 

public class PrimeNumber{    
 public static void main(String args[]){    
  int i,a=0,flag=0;      
  int b=3;//it is the number to be checked    
  a=b/2;   
   
// Condition written for Exclude 0 and 1   
if(b==0||b==1){
System.out.println(b+" 0 and 1 can not be prime number"); }else{ for(i=2;i<=a;i++){ if(b%i==0){ System.out.println(b+" is not prime number"); flag=1; break; } } if(flag==0) { System.out.println(b+" is prime number"); } } } }

Que : Write a Program to find a Number is Palindrome number or not in Java ?


Ans :  A Palindrome is a Number that remains same when its digit are reversed , In This Program we are going to check  '545' is Palindrome or not

Program :


public class PalindromeNumber{  
 public static void main(String args[]){  
  int a,sum=0,temp; 
// no to check palindrome or not   
  int n=545;
    temp=n;    
  while(n>0){    
   a=n%10;  //getting remainder  
   sum=(sum*10)+a;    
   n=n/10;    
  }    
  if(temp==sum)    
   System.out.println("palindrome number ");    
  else    
   System.out.println("not palindrome");    
}  
}  

Que : Write a Factorial program in Java ?


Ans   :  The result of multiplying a sequence of descending natural numbers down to 1 , In Math Factorial of n is denoted by n! , Like : 5!=5*4*3*2*1

we are going to write factorial program in Two way :

1. Factorial program using Loop iteration
2. Factorial program using recursion

Type 1 :  Factorial program using Loop iteration 


Program :


public class FactorialProgram{  
 public static void main(String args[]){  
  int i,f=1;  
  int n=5;//It is the number to calculate factorial    
  for(i=1;i<=n;i++){    
      f=f*i;    
  }    
  System.out.println("Factorial of "+n+" is: "+f);    
 }  
}  

Type 2 :  Factorial program using recursion


public class FactorialProgram{  
 public static int factorial(int n){    
  if (n == 0)    
    return 1;    
  else    
    return(n * factorial(n-1));    
 }    
 public static void main(String args[]){  
  int i,f=1;  
  int n=4;//It is the number to calculate factorial    
  f = factorial(n);   
  System.out.println("Factorial of "+n+" is: "+f);    
 }  
}  

Que : Write a Program to Check Armstrong no in Java ?


Ans   : Armstrong number is a number which is equal to sum of cubes of its digit .
Like : 371 = (3*3*3) + (7*7*7) + (1*1*1) , Here we are going to write a program that 371 is  armstrong number or not .


public class ArmstrongProgram{  
  public static void main(String[] args)  {  
    int a=0,b,temp;  
    int n=371;//It is the number to check armstrong  
    temp=n;  
    while(n>0)  
    {  
    b=n%10;  
    n=n/10;  
    a=a+(b*b*b);  
    }  
    if(temp==a)  
    System.out.println(n +" is aarmstrong number");   
    else  
        System.out.println(n +" is Not armstrong number");   
   }  
}  


How to read and write from Excel File in Selenium : Apache POI and JXL

Java provides different API to Read and Write a File with help of Selenium. In this Post, we will learn how can we read and write from Excel file by using Java IO package,JXL and Apache POI library.
            If your are using any Automation Framework you must know About Read and Write fro Excel, We have to use This Concept while working in Data Driven Framework .


Step to Read Data from Excel Using Apache POI jar


To Read or Write From Excel,Apache Community provides a very widely used library POI. This library have features to read and write both XLS and XLSX file format of Excel.
HSSF implementation is provided by POI library to read 'XLS' Files and XSSF implementation of POI library to read 'XLSX' File ,Lets go to Deep Die .......


  • For user who is using Maven Project can copy Dependency from here 
  • 
    
        org.apache.poi
        poi
        3.17
    
       


Types of  Files in MS-Excel 

  • .XLS File
  • .XLSX File


Types of Classes and InterFace in Apache POI 


Apache Interface and Classes



 Read Data from Excel File


  • Go To Java Project
  • Right Click on Java Project
  • Create a New Folder with Name DataFromExcel
  • Copy Any Blank Excel File from Your PC and Paste Inside Folder 'DataFromExcel'
  • Open Excel File 
  • Enter The Excel Sheet Name 'LoginDataSheet'
  • Enter Any Website Login Credential Whom you want To Read

LoginDataSheet


SheetName
  
package com.abof.scripts;  // As Per Your Java Project Name

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadQaMantraExcelFile {

    
    public void readExcelFile(String filePath,String fileName,String sheetName) throws IOException{

    //Create an object of File class to open xlsx file

    File file =    new File(filePath+"\\"+fileName);

    //Create an object of FileInputStream class to read excel file

    FileInputStream inputStream = new FileInputStream(file);

    Workbook workbook = null;

    //Find the file extension by splitting file name in substring  and getting only extension name

    String fileExtensionName = fileName.substring(fileName.indexOf("."));

    //Check condition if the file is xlsx file

    if(fileExtensionName.equals(".xlsx")){

    //If it is xlsx file then create object of XSSFWorkbook class

    workbook = new XSSFWorkbook(inputStream);

    }

    //Check condition if the file is xls file

    else if(fileExtensionName.equals(".xls")){

        //If it is xls file then create object of XSSFWorkbook class

       workbook = new HSSFWorkbook(inputStream);

    }

    //Read sheet inside the workbook by its name

    Sheet sheet = workbook.getSheet(sheetName);

    //Find number of rows in excel file

    int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();

    //Create a loop over all the rows of excel file to read it

    for (int i = 0; i < rowCount+1; i++) {

        Row row = sheet.getRow(i);

        //Create a loop to print cell values in a row

        for (int j = 0; j < row.getLastCellNum(); j++) {

            //Print Excel data in console

            System.out.print(row.getCell(j).getStringCellValue()+"|| ");

        }
    }
    }
    

    //Main function is calling readExcel function to read data from excel file

    public static void main(String [] args) throws IOException{

    //Create an object of ReadQaMantraExcelFile class

    ReadQaMantraExcelFile objExcelFile = new ReadQaMantraExcelFile ();

    //Prepare the path of excel file

    String filePath = System.getProperty("user.dir")+"\\src\\testData";

    //Call read file method of the class to read data

    objExcelFile.readExcelFile(filePath,"data.xlsx","LoginDataSheet");

    }

}



 Write Data To Excel File


package com.abof.scripts;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteqamantraExcelFile {
               public void writeExcel(String filePath,String fileName,String sheetName,String[] dataToWrite) throws IOException{

        //Create an object of File class to open xlsx file

        File file =    new File(filePath+"\\"+fileName);

        //Create an object of FileInputStream class to read excel file

        FileInputStream inputStream = new FileInputStream(file);

        Workbook qamantraWorkbook = null;

        //Find the file extension by splitting  file name in substring // and getting only extension name

 String fileExtensionName = fileName.substring(fileName.indexOf("."));

        //Check condition if the file is xlsx file

        if(fileExtensionName.equals(".xlsx")){

        //If it is xlsx file then create object of XSSFWorkbook class

        qamantraWorkbook = new XSSFWorkbook(inputStream);

        }

        //Check condition if the file is xls file

        else if(fileExtensionName.equals(".xls")){

      //If it is xls file then create object of XSSFWorkbook class

            qamantraWorkbook = new HSSFWorkbook(inputStream);

        }

        

    //Read excel sheet by sheet name    

    Sheet sheet = qamantraWorkbook.getSheet(sheetName);

    //Get the current count of rows in excel file

    int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();

    //Get the first row from the sheet

    Row row = sheet.getRow(0);

    //Create a new row and append it at last of sheet

    Row newRow = sheet.createRow(rowCount+1);

    //Create a loop over the cell of newly created Row

    for(int j = 0; j < row.getLastCellNum(); j++){

        //Fill data in row

        Cell cell = newRow.createCell(j);

        cell.setCellValue(dataToWrite[j]);

    }

    //Close input stream

    inputStream.close();

    //Create an object of FileOutputStream class to create write data //in excel file

    FileOutputStream outputStream = new FileOutputStream(file);

    //write data in the excel file

    qamantraWorkbook.write(outputStream);

    //close output stream

    outputStream.close();
    
    }

    
    public static void main(String args []) throws IOException{

        //Create an array with the data in the same order in which you //expect to be filled in excel file

        String[] valueToWrite = {"abc@gmail.com","Pass@123"};

        //Create an object of current class

   WriteqamantraExcelFile objExcelFile = new WriteqamantraExcelFile();

//Write the file using file name, sheet name and the data to be filled

        objExcelFile.writeExcel(System.getProperty("user.dir")+"\\src\\testData","data.xlsx","LoginDataSheet",valueToWrite);

    }

}






                                              

How To Download Apache POI jar to read and write data from MS-Excel 07-10

In this Post, we will learn how can we Download Apache POI jar , Follow Easy Steps To Download Jar File .


  • Click on 'poi-bin-3.17-20170915.zip' named link under 'Binary Distribution'  Section  , Link under Red Highlighted rectangle shape
   

Apache POI 


  • Now Select first Link of Page as mentioned in Image Link under Red Highlighted rectangle shape


Apache POI 


  • A Zip file Will be Downloaded after Some Time ,Now Unzip(Extract) the Zip folder, Downloading part have been Completed and user should add to jars in Build Path so now let's learn How To do That.



How To Add Jar Files in java Build path

Follow certain step to add jar in Build Path -:

  • Open Eclipse To Add Jars in Build Path you should Have Eclipse if You d'nt have then Click Link To Downloading and installation Tutorial of Eclipse Eclipse Installation 
  • Go to your Java Project , if You d'nt know How To create Java Project Follow This Link to Create Java Project


  • Right click on java project 
  • Select an option 'Build Path' > Select 'Configure Build Path'
  • Select 'Library Section'
  • Select 'Add External Jars'

JAVA Build Path

  • File Browse Window will open  >  Select Below Mentioned jar and Click on 'OPEN' button
     

Apache POI Jars

       

Apache POI Jars



 Note: All jars Will available in Different Folder of  'Apache POI'

  • Your Jar File have added > click on 'Apply' and 'OK' Button
  • All jars would be now added to build path ,it will be appear like below mentioned image

JAVA Build Path


Now you have done all Steps ,you are ready to go for Data Driven Framework or Read and Write from Excel 
  


How to use Explicit and Implicit Wait in Selenium

Implicit Wait :


An implicit wait tells WebDriver or Selenium Scripts to poll the DOM for a certain amount of time when Selenium Scripts trying to find an Object/Element or Object/Elements if they are not visible or Interactable.
     
                              Implicit wait condition may slow down your tests Script Execution when an application responds normally, It will wait for each Object/Element appearing in the DOM and increase the overall tests Script Execution duration. It is Highly Suggested to avoid or reduce the usages of an Implicit wait and try to handle synchronization issues with an Explicit wait , which is much Effective ,Efficient and Convenient to use as compared to an Implicit wait .

Syntax of Implicit Wait in Selenium

 driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

How to use Implicit wait for 10 seconds


driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);


Program


package QaMantra.test;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;

public class AppTest {

 

 protected WebDriver driver;

 @Test

 public void QaMantratutorials() throws InterruptedException

 {

 System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );

 driver = new ChromeDriver();

 driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;

 String ExpectedTitle = "Demo QaMantra Page";

 String aTitle = "" ;

 // launch Chrome and redirect it to the Base URL

 driver.get("http://www.qamantra.com/2018/01/how-to-use-explicit-and-implicit-wait.html" );

 //Maximizes the browser window

 driver.manage().window().maximize() ;

 //get the actual value of the title

 QaMantraTitle = driver.getTitle();

 //compare the actual title with the expected title

 if (QaMantraTitle.equals(ExpectedTitle))

 {

 System.out.println( "Test Passed") ;

 }

 else {

 System.out.println( "Test Failed" );

 }

 //close browser

 driver.close();

}

}
                                   
                                      Implicit wait Have two parameters, the first parameter is time as an integer value and the second parameter is time Unit aceptable in SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS, DAYS, HOURS, etc.

Explicit Wait :


Explicit wait tell the WebDriver to wait for certain time on basis of certain Expected conditions before throwing an "ElementNotVisibleException" exception ,Explicit wait is specific wait applied only for specified elements. Explicit wait have better flexibility then Implicit wait. 
             
                                           Selenium WebDriver provides the 'WebDriverWait' and 'ExpectedCondition' classes to Implement Explicit wait condition , 'ExpectedCondition' class provides a set of predefined conditions to wait before proceeding further
in Script.
            
                                        
     
Predefined conditionSelenium WebDriver (Java)
An element is visible and enabledelementToBeClickable(By locator)
Presence of an elementpresenceOfElementLocated(By locator)
An element is selectedelementToBeSelected(WebElement element)
Specific text present in an elementtextToBePresentInElement(By locator,
java.lang.String text)
TitletitleContains(java.lang.String title)
Element valuetextToBePresentInElementValue(By locator, java.lang.String text)


     

Explicit Wait Condition

Syntax

                         
WebDriverWait wait = new WebDriverWait(driver,TimeOut);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By locator));

                                     
  TimeOut is an Integer Value which have unit is Seconds .
              


package QaMantra.test;
 
import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.By;
 
import org.openqa.selenium.WebDriver;
 
import org.openqa.selenium.chrome.ChromeDriver;
 
import org.testng.annotations.Test;
 
public class QaMantra {
 
  
 
 public WebDriver driver;
 
 @Test
 
 public void QaMantratutorials() throws InterruptedException
 
 {
 
 System.setProperty ("webdriver.chrome.driver",".\\chromedriver.exe" );
 
 driver = new ChromeDriver();
 
 //Implicit wait
 driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS) ;
 
 String ExpectedTitle = "Demo QaMantra Page";
 
 String aTitle = "" ;
 
 // launch Chrome and redirect it to the Base URL
 
 driver.get("http://www.qamantra.com/2018/01/how-to-use-explicit-and-implicit-wait.html" );
 
 //Maximizes the browser window
 
 driver.manage().window().maximize() ;
 
 //get the actual value of the title
 QaMantraTitle = driver.getTitle();
 
 //compare the actual title with the expected title
 
 if (QaMantraTitle.equals(ExpectedTitle))
 
 {
 
 System.out.println( "Test Passed") ;
 
 }
 
 else {
 
 System.out.println( "Test Failed" );
 
 }
  //Explicit wait 
WebDriverWait wait  =  new WebDriverWait(driver,10);
WebElement QaMantra  =  wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//div[@class='widget-content popular-posts'])[1]")));
QaMantra.click();

}
};