Results for Selenium Tutorial

How To Take ScreenShot in Selenium in Three Quick Ways

March 30, 2016
Hope you enjoyed my last post on how to get webElement count. Now with this post, I am going to write a code that will take screenshot with Selenium.It is not something new.It is already there in different websites. I am just compiling these into one post and that is as per normal basic framework.
So to start with I will assume, there is a small framework in place. That is the driver class which will have all the methods. For advance stuff,we might have a separate helper class too.
So lets get started:
The first approach: Using TakesScreenshot
public void getscreenshot() throws Exception 
     {
             File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
             FileUtils.copyFile(scrFile, new File("<<path with name of the file>>"));
     }
The second Approach: We will have a overloaded methods of takingscreenshot where it takes no parameter or one parameter which is the element.Also there are two ways to implement it. One is to give your element name and get the screenshot file as element name or set the file name with time stamp
public void takeSceenshot() throws IOException
 {
  TakesScreenshot oscn=(TakesScreenshot)driver;
  File oscnShot= oscn.getScreenshotAs(OutputType.FILE);
  File destfile=new File("D:\\My_projects\\Projects\\TestBase\\src\\Base\\Test.jpg");
  FileUtils.copyFile(oscnShot, destfile);
 }
 public void takeSceenshot(String elementType) throws IOException
 {
  TakesScreenshot oscn=(TakesScreenshot)driver;
  File oscnShot= oscn.getScreenshotAs(OutputType.FILE);
  File destfile=new File("D:\\My_projects\\Projects\\TestBase\\src\\Base\\Test"+elementType+".jpg");
  File destfile1=new File("D:\\My_projects\\Projects\\TestBase\\src\\Base\\Test"+GetTimeStampValue()+".jpg");
  FileUtils.copyFile(oscnShot, destfile);
  FileUtils.copyFile(oscnShot, destfile1);
 }
 public  String GetTimeStampValue()throws IOException{
     Calendar cal = Calendar.getInstance();       
     Date time=cal.getTime();
     String timestamp=time.toString();
     System.out.println(timestamp);
     String systime=timestamp.replace(":", "-");
     System.out.println(systime);
     return systime;
 }

Third Option could be:This using pure java with robot class.
protected void takeScreenShotMethod(){
     try{
         Thread.sleep(10000);
         long id = Thread.currentThread().getId();
         BufferedImage image = new Robot().createScreenCapture(new Rectangle(
             Toolkit.getDefaultToolkit().getScreenSize()));
         ImageIO.write(image, "jpg", new File("./"
             + id + "screenshot.jpg"));
     }
     catch( Exception e ) {
         e.printStackTrace();
     }
 }

I worked with these three ways to take screenshots.But mostly I like the second one. Now let us understand when we should use it. If the webpage is opening with some popup ,like rediff.com, or if in some cases webpage is minimized,It will take the screenshot of the webelement or the webpage even if new popups are opened.
But suppose you are using one application like desktop automation using selenium with a third party jars or applet automation, in that case we will go with third approach.
Do let me know if you agree or disagree with me.

How To Take ScreenShot in Selenium in Three Quick Ways How To Take ScreenShot in Selenium in Three Quick Ways Reviewed by Animesh Chatterjee on March 30, 2016 Rating: 5

How To Convert JUnit Report Produced by ANT to Excel

August 26, 2015
ANT-Excel Reporting is an important area where automation needs to fine-tune.
Every test should have some objectives. That is finite and achievable. So reports coming straight from automation tool should tell clearly the result of the testcase. There could be two options pass or failed. If failed if it gives the reason and if can pinpoint if there is already any bug on that, that would be awesome. Otherwise result may mislead the testing.Result should also provide screenshots for passed and failed, testdata, environment details , step details and other information to nail the issue.
Now analysis of these failures are tedious and boring job, takes several time of a test engineers.With meaningful failure message, it is possible to automate the result analysis part. the below section talks about the automation of such report coming straight from JUnit.Many a times, we need to convert JUnit report to Excel. Some need this for his own reporting purpose. Functional QA needs it for analysis and documentation. Automation test engineers need this converted data for
further script/test fix.
I tried to google the same.
I found this-Convert an XML file into an Excel spreadsheet 
with this technique. Here the technique is little complex.
I found in google many test engineers need this for their analysis.
 And most of them around 16 links in google to find out the failed
and Error testcases.

I am creating a simple project to extract all errors and failure testcases in excel.

To run this what you need:
Java 1.7
JSoup latest
Eclipse
POI
Before we really start please go through the below links for further understanding:
  1. JSoup A Nice Initiative To Fetch Information From HTML
  2. How To Read Data From HTML Via JSoup In Java
The algorithm is as follows:
  1. Take JUnit report from User using swing input
  2. Read all tables and filter out errors and failures into two different lists using JSoup
  3. Create Excel and sheet using POI
  4. Put all data into the sheet using POI and java
Implementation:
So the first step take eclipse or any java editor. Install or extract into a folder. Create a workspace for this. Now create a project. The structure of the project will look like--
Project Structure

























Name of the project-Result Analyser.
Now while coding our first objective to create
 a user interface. From this interface user will
 will provide JUnit report to the system.

input
Code for user Input:

package main.java;
import javax.swing.JOptionPane;
public class Client {
public static void main(String[] args) throws Exception { 
 
        ReadHTML readHtml=new ReadHTML(); 
        readHtml.getValues(JOptionPane.showInputDialog("Please input mark for test 1: "),"Test"); 
        CreateExcelFile cef=new CreateExcelFile(); 
        cef.getExcelFileName();

    }

} 

Now I am creating an Object ReadHTML.So let us implement ReadHTML

package main.java;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class ReadHTML {
 public  void  getValues(String url,String SheetName) throws Exception
 {
  String overViewSummaryURL=url+"overview-summary.html";
  String allFailureDetailsURL=url+"alltests-fails.html";
  String allErrorDeatilsURL=url+"alltests-errors.html";
  System.out.println("Processing Overview Summary");
  URL getUrl=new URL(overViewSummaryURL);
  Document doc = Jsoup.parse(getUrl, 3000);
  Element table = doc.select("table[class=details]").first();
  Iterator<Element> iteh = table.select("th").iterator();
  //This is for fetching header values
  String test= iteh.next().text();
  String fail= iteh.next().text();
  String err= iteh.next().text();
  String knonIss=iteh.next().text();
  String pass= iteh.next().text(); 
  String skip= iteh.next().text();
  String suc_rate=iteh.next().text();
  String time=iteh.next().text();

  Iterator<Element> ite = table.select("td").iterator();

  //This is for fetching row values
  String testV=ite.next().text();
  String failV=ite.next().text();
  String errorV=ite.next().text();
  String knownIssueV=ite.next().text();
  String passV=ite.next().text();
  String skipV=ite.next().text();
  String sucv=ite.next().text().split(":")[1].split("%")[0].trim();
  String timeV=ite.next().text();

  System.out.println("Value of: "  +test+  " is " + testV );
  System.out.println("Value of: "  +fail+  " is " + failV);
  System.out.println("Value of: "  +err+  " is "  +errorV);
  System.out.println("Value of: "  +knonIss+  " is " +knownIssueV );
  System.out.println("Value of: "  +pass+  " is "  +passV);
  System.out.println("Value of: "  +skip+  " is "  +skipV );
  System.out.println("Value of: "  +suc_rate+  " is " + sucv);
  System.out.println("Value of: "  +time+  " is " +timeV );
  System.out.println("Processing All Failure Summary");
  getUrl=new URL(allFailureDetailsURL);

  Document docfailure = Jsoup.parse(getUrl, 3000);
  Elements tableFailure = docfailure.select("table[class=details]");

  int rowCount=tableFailure.select("tr[class=Failure]").size();
  

  System.out.println(rowCount+"row");

  System.out.println("Processing All Failure Summary result");

  List<List> recordToAdd = new ArrayList<List>();
  
  List<String> headerRow = new ArrayList<String>();
  
  headerRow.add("Class Name");
  headerRow.add("Script Name");
  headerRow.add("altId");
  headerRow.add("TestCase Name");
  headerRow.add("Status");
  headerRow.add("Log Information");
  headerRow.add("Class Path");
  headerRow.add("Reason for Failure");
  
  recordToAdd.add(headerRow);
  ArrayList<String>[] firstRow_rowfail_tds;
              if(Integer.parseInt(errorV)>0) {
            //List<String> firstRow_rowfail_tds = new ArrayList<String>();
            firstRow_rowfail_tds = (ArrayList<String>[]) new ArrayList[rowCount + Integer.parseInt(errorV)];
                    }
  else
                    {
            firstRow_rowfail_tds = (ArrayList<String>[]) new ArrayList[rowCount];
                    }
            int i=0;
          for (Element tablefail : docfailure.select("table[class=details]")) {
           for (Element rowfail : tablefail.select("tr[class=Failure]")) {
    Elements tds = rowfail.select("td");
                
    System.out.println("Class Name - " + tds.get(0).text());  
    System.out.println("Script Name - " + tds.get(1).text());
    System.out.println("altId - " + tds.get(2).text());
    System.out.println("TestCase Name - " + tds.get(3).text());
    System.out.println("Status- " + tds.get(4).text());
    System.out.println("URL-->"+tds.select("a").attr("href"));
    System.out.println("");  
   firstRow_rowfail_tds[i] = new ArrayList<String>();
     
     firstRow_rowfail_tds[i].add((String) tds.get(0).text());
     firstRow_rowfail_tds[i].add((String) tds.get(1).text());
     firstRow_rowfail_tds[i].add((String) tds.get(2).text());
     firstRow_rowfail_tds[i].add((String) tds.get(3).text());
     firstRow_rowfail_tds[i].add((String) tds.get(4).text());
     firstRow_rowfail_tds[i].add((String) tds.get(5).text());
     firstRow_rowfail_tds[i].add((String) getClassInformation(tds.select("a").attr("href"),(String) tds.get(0).text()));
                    recordToAdd.add(firstRow_rowfail_tds[i]);
     System.out.println(recordToAdd);
     i=i+1;
     System.out.println(i+"val of i");
     if (i==tablefail.select("tr[class=Failure]").size())
      break;
   }
  }
        System.out.print("errorV"+errorV);
  if(Integer.parseInt(errorV)>0)
  {
     getUrl=new URL(allErrorDeatilsURL);
  Document docError = Jsoup.parse(getUrl, 3000);
  Elements tableError = docError.select("table[class=details]");
  int rowCountError=tableError.select("tr[class=Error]").size();
     System.out.println(rowCountError+"row");
  System.out.println("Processing All Error Summary result");
  int j=0;
  for (Element tablefailError : docError.select("table[class=details]")) {
   for (Element rowfailError : tablefailError.select("tr[class=Error]")) {
    Elements tds = rowfailError.select("td");
                
    System.out.println("Class Name - " + tds.get(0).text());  
    System.out.println("Script Name - " + tds.get(1).text());
    System.out.println("altId - " + tds.get(2).text());
    System.out.println("TestCase Name - " + tds.get(3).text());
    System.out.println("Status- " + tds.get(4).text());
    System.out.println("");  
     firstRow_rowfail_tds[i+j] = new ArrayList<String>();
     firstRow_rowfail_tds[i+j].add((String) tds.get(0).text());
     firstRow_rowfail_tds[i+j].add((String) tds.get(1).text());
     firstRow_rowfail_tds[i+j].add((String) tds.get(2).text());
     firstRow_rowfail_tds[i+j].add((String) tds.get(3).text());
     firstRow_rowfail_tds[i+j].add((String) tds.get(4).text());
     firstRow_rowfail_tds[i+j].add((String) tds.get(5).text());

     firstRow_rowfail_tds[i].add((String) getClassInformation(tds.select("a").attr("href"),(String) tds.get(0).text()));
     recordToAdd.add(firstRow_rowfail_tds[i+j]);
     System.out.println(recordToAdd);
     j=j+1;
     System.out.println(j+"val of j");
     if (j==tableError.select("tr[class=Error]").size())
      break;
   }

        }
  }
  System.out.print("recordToAdd"+recordToAdd);
  CreateExcelFile cls = new CreateExcelFile(recordToAdd,SheetName);


 }

 private String getClassInformation(String attr, String text) {
        attr.toString();
  // TODO Auto-generated method stub
  return null;
 }

 
 
}


Now I am creating another object class:CreateExcelFile CreateExcelFile cef=new CreateExcelFile(); So let us implement CreateExcelFile class:

package main.java;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

/*
 * Here we will learn how to create Excel file and header for the same.
 */
public class CreateExcelFile {

  int rownum = 0;
  HSSFSheet firstSheet,SecondSheet ;
 Collection<File> files;
  HSSFWorkbook workbook;
 File exactFile;
 {
  workbook = new HSSFWorkbook();
  firstSheet = workbook.createSheet("FIRST SHEET");


  Row headerRow = firstSheet.createRow(rownum);
  headerRow.setHeightInPoints(40);
 }
 public CreateExcelFile(){
 }
 CreateExcelFile(List<List> l1,String FileName) throws Exception {
  FileOutputStream fos = null;
  try {
   workbook = new HSSFWorkbook();
   firstSheet = workbook.createSheet("FIRST SHEET");

   }
        catch (Exception e)
        {
   e.printStackTrace();
  }
  
  try {
                for (int j = 0; j < l1.size(); j++) {
             Row row = firstSheet.createRow(j);
    List<String> l2= l1.get(j);
    for(int k=0; k<l2.size(); k++)
    {
     Cell cell = row.createCell(k);
     cell.setCellValue(l2.get(k));
    }
    rownum++;
   }

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

  }

  fos=new FileOutputStream(new File(getPath(FileName)));
        System.out.print(getPath(FileName));
  HSSFCellStyle hsfstyle=workbook.createCellStyle();
  hsfstyle.setBorderBottom((short) 1);
  hsfstyle.setFillBackgroundColor((short)245);
  workbook.write(fos);
        fos.close();
        
        
 }
    
public String getTimeStamp()

{
return new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime()); 
}
public String getPath(String FileName) throws IOException
{
 String path=new File(".").getCanonicalPath() + File.separator;
 //path=path+getTimeStamp()+"analysis"+".xls";
    path=path+"analysis_"+FileName+".xls";
 return path;
}

public String getExcelFileName()
{String path="";
    try {
         path=new File(".").getCanonicalPath() + File.separator;
    } catch (IOException e) {
        e.printStackTrace();
    }
    int totalFileCount = 0;
     int fileCount = 0;
     ArrayList<String> aList = new ArrayList<String>();
    File folder = new File(path);
    File[] listOfFilesInDirectory = folder.listFiles();
    try {
        for (int numberOfFilesInFolder = 0; numberOfFilesInFolder < listOfFilesInDirectory.length; numberOfFilesInFolder++) {

            if (listOfFilesInDirectory[numberOfFilesInFolder].isFile()) {
                totalFileCount++;
                String files = listOfFilesInDirectory[numberOfFilesInFolder]
                        .getName();
                if (files.endsWith(".xls") || files.endsWith(".XLS")
                        || files.endsWith(".xlsx")
                        || files.endsWith(".XLSX")) {
                    aList.add(files);
                    fileCount++;
                }
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Total file count = " + totalFileCount);
    System.out.println("Required file count = " + fileCount);

    return "";
}
}

That's it. Now run your client to fetch the JUnit report. After Processing it will create the excel with all failures,Errors and known issues with the failure message in excel.

The output will be:

The output excel will look like-
With this report a automatic excel will be generated to give proper guidance  to automation test engineer to analyze more in details.
As we know advertisement plays a great role or huge role in terms of successful products. It creates the awareness among the consumer of the products. Sharing the extract from test automation result with management and other stakeholders play a significant role for advertisement of automation. It is having multi folded benefits..
1. All stakeholders become serious while developing or making changes in application. Slowly they tend to think about testing team which intern gives birth of test driven development.
2.All shareholders become aware about the effort automation test engineers putting into automating the application. This gives a solid management backing.
3. Bugs caught in automation gets visible in very early stage in very quick time. Also automation logs shows the different areas, it touched. Functional QA and dev team will have a clear idea where the application is working fine and where it is broken.
How To Convert JUnit Report Produced by ANT to Excel How To Convert JUnit Report Produced by ANT to Excel Reviewed by Animesh Chatterjee on August 26, 2015 Rating: 5

How to Resolve Issue With Size() Function in Selenium for ChromeDriver

July 31, 2015

Issue Details:
In selenium execution out of ten runs six run it gives
correct result in Firefox and Internet Explorer.
But the same failed in Chrome. Always gives wrong
count when element.Size() function is triggered.
System.out.println(driver.findElements())
(By.xpath("//*[@class='test-box']")).size());



How to Solve:



1. First let us check if chrome is rendering the xpath correctly. Check the xpath.


2. Secondly,let us check if application is taking longer time to load in chrome. Use some wait time.


How to Resolve Issue With Size() Function in Selenium for ChromeDriver How to Resolve Issue With Size() Function in Selenium for ChromeDriver Reviewed by Animesh Chatterjee on July 31, 2015 Rating: 5

Issues with Sendkeys Not Working With Different Browser

July 31, 2015


Issue Details:With the latest IEDriver, It is seen sendKeys method is not able to push data into testarea. The same method works great with Firefox and Chrome.

There is one more issue upon clicking on save button, the text entered, gets disappear.

What to check:

The check points are:
Check the version of Selenium,IEDriverServer.exe, Internet Explorer [For IE11, we need selenium 2.44 or above.]
Resolution:
There might be a workaround-Just press a Tab using Sendkeys(“TAB”). It might trigger the underlaying javascript
The main issue is problem related to nativeEvents in IE.
Issue Details:
Sendkeys may send data one character by one character. As a result execution becomes very slow.

What to check:
The driver version. In 64 bit of drivers , It may so happen. Downgrade the driver to 32 bit.Also you need to check the same version of IEDriverServer.exe. So basically if you are using 32 bit of browser, the driver has to be 32 bit.

Issue Details:
Sendkeys may send data partially in parallel mode of execution but sends full string while running in one thread.

What to check:
Check the application type.It is very common in Angular JS applications.Always upgrade the library to the latest Angular JS.
if you can not upgrade the Angular JS,use the following code:

var i;
for(i = 0; i < toxtToSend.length; i++){
EditBox.sendKeys(toxtToSend.charAt(i));
}
or we can try with java script executor class:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('gbqfq').value = 'Test';");
one more solution could be to use java.awt package:
Initial phase set the focus to the element and write the below code:

driver.findElemnt(by.xpath("abc")).setfocus();
paste();

public static void paste() throws AWTException
{
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
}
Issue Details:
Sendkeys does not work properly when using gecodriver.

What to check:
Either use
System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE,"false");
 or using Firefox options setting up the capabilities

Issues with Sendkeys Not Working With Different Browser Issues with Sendkeys Not Working With Different Browser Reviewed by Animesh Chatterjee on July 31, 2015 Rating: 5

How To Resolve OSError : WinError 6 The Handle is Invalid

July 29, 2015

This is a very interesting failure. When we do prototype, say with 10 testcases,
Webdriver seems to have behave correctly. All testcases passes. Now when we
put out test suite,after execution of 10-12 testcases,It starts failing/Skipping or
erroring out. The trace we get is listed below:

Traceback (most recent call last):
File"C:\Users\avraciu\workspace\AutomationTesting_v2.0src\Home\IPSEC\
CreateIPSEC\Create_IPSEC_GW_Term_Monthly.py", line 21, in
setUpself.driver = webdriver.Firefox()
File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\webdriver.py",
line 64,in __init__self.binary, timeout),
File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\
extension_connection.py",
 line 51, in __init__self.binary.launch_browser(self.profile)
File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\
firefox_binary.py", line 69,
 in launch_browser
self._start_from_profile_path(self.profile.path)
File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\firefox_binary.py",
line 92,
 in _start_from_profile_path  env=self._firefox_env)
File "C:\Python34\lib\subprocess.py", line 754, in __init___cleanup()
File "C:\Python34\lib\subprocess.py", line 474, in _cleanup
res = inst._internal_poll(_deadstate=sys.maxsize)
File "C:\Python34\lib\subprocess.py", line 1146, in _internal_poll
if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
OSError: [WinError 6] The handle is invalid


The Workaround:
Checkout the configuration may be that is wrong.Mostly the latest browser version and WebDriver version do not match. Downgrade one level down for browser. It should work. On the next step downgrade the Webdriver version as well.
Next is to check the version of the OS as well as the version of the installed software's. Like-the eclipse,phython,webDriver etc. They should be as per OS. I mean if your’s is a 64 bit OS. Please use same 64 bit application as well. 
How To Resolve OSError : WinError 6 The Handle is Invalid How To Resolve OSError : WinError 6 The Handle is Invalid Reviewed by Animesh Chatterjee on July 29, 2015 Rating: 5

Find Repeated Character From An Array of String In Java/Selenium/OATS

July 04, 2015

You have a array of strings e.g ["abcd","aabcd",xyz", "ccbc"] find the strings in
which characters are repeated.Output would be ["aabcd","ccbc"].

Logic:: Need to check if the current position and the next position are having the same character or not.If they have same character they are repetitive characters.


//You have a array of strings e.g ["abcd","aabcd",xyz", "ccbc"] find the strings in 
//which characters are repeated.Output would be ["aabcd","ccbc"].
//Author:Animesh



public class RepeatString {
 
 static String[] names={"abcd","aabcd","xyz", "cdbbc"};
 
 public static void main(String[] args) throws InterruptedException {
  for(int i=0;i<names.length;i++)
  {
   if(repeatCalulator(names[i]))
   {
    System.out.println(names[i]);
   }
  }
  
  
 }
 
 public static boolean repeatCalulator(String name)
 {
  boolean flag=false;
  int sizeoftheString=name.length();
  for(int j=1;j<sizeoftheString;j++)
  {
  if(name.charAt(j-1)==name.charAt(j))
  {
   
   flag=true;
   break;
   
  }
    
  }
  return flag;
  
 }

}



Image source:www.javaclass.info
Find Repeated Character From An Array of String In Java/Selenium/OATS Find Repeated Character From An Array of String In Java/Selenium/OATS Reviewed by Animesh Chatterjee on July 04, 2015 Rating: 5

How To Get Table Rows in Selenium??

June 16, 2015
This is a very important implementation for selenium to find rows of a given table.

Below is an example of a table.

Name Salary
Animesh 5000
Rohan  7000
Now if we want to get rows of the table,we need to perform the following steps:

  1. First go Inspect element or firebug to determine the table name or id.[we can get the table by tag name also]

2.Now the corresponding code goes like
int count = 0;
List rows = driver.findElements(By.xpath("//table//tr"));
for(WebElement row: rows){
  if(row.isDisplayed())
    count++;
}
System.out.println("The number of rows that are visible is: "+ count);

instead xpath we can also find it by id or name like---
WebElement table=driver.findElement(By.id("Employee"));
if name is there
WebElement table=driver.findElement(By.name("name of the table"));
List  rows=table.findElement(By.tagName("tr"))
rows.size();
How To Get Table Rows in Selenium?? How To Get Table Rows in Selenium?? Reviewed by Animesh Chatterjee on June 16, 2015 Rating: 5

How To Resolve UnhandledAlertException While working with Alert Box in WebDriver in Selenium

December 11, 2014
Many a times, while testing web application, we face such situation where we need to handle javascript alert from our webdriver code in selenium.

And it is also very common that we get the below written UnhandledAlertException   while running our code.

The code may look like-
:org.openqa.selenium.UnhandledAlertException: Modal dialog present: The account has been modified, discard changes?
Build info: version: '2.39.0', revision: 'ff23eac', time: '2013-12-16 16:12:12'
System info: host: 'HOST-ABCD', ip: '10.56.23.2345, os.name: 'Windows Server 2008 R2', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_51'
Session ID: ad3746bf-4c03-4de9-9bb8-17831538c562
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{platform=WINDOWS, javascriptEnabled=true, elementScrollBehavior=0, ignoreZoomSetting=false, enablePersistentHover=true, ie.ensureCleanSession=false, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=8, ie.usePerProcessProxy=false, cssSelectorsEnabled=true, ignoreProtectedModeSettings=false, requireWindowFocus=false, handlesAlerts=true, initialBrowserUrl=http://localhost:9493/, ie.forceCreateProcessApi=false, nativeEvents=true, browserAttachTimeout=0, ie.browserCommandLineSwitches=, takesScreenshot=true}]

The code we use to combat the alert box is given below:
driver.switchTo().alert().accept();


Let us understand why this exception comes then:
It is seen many a time the application is slow in nature and selenium is trying to execute the code before the alert pop up. So the next statement will have this exception. Many coder try to put a Thread.Sleep(5) before the above code. But the success rate to avoid this exception is upto the speed of application.

So how to resolve this issue?

Well instead of Thread.Sleep(5) use a more correct method..
WebDriverWait wait =new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();
So this code will wait for the alert to come and then it will click on ok what accept button.

Problem might solve, but is this the correct solution??

Probably, No!!!.
This condition does not hold good for the case where the pop up do not appear. It will go to infinite loop. Let us make it little safe:
public boolean isAlertPresent(){
        try{
            driver.switchTo().alert();
            return true;
        }//try
        catch(Exception e){
            return false;
        }//catch
    }

and
if(isAlertPresent()){
            driver.switchTo().alert();
            driver.switchTo().alert().accept();
            driver.switchTo().defaultContent();
        }


There is one more beautiful way to solve this issue:


for(String s: webDriver.getWindowHandles()){
 //see if alert exists here.
}






How To Resolve UnhandledAlertException While working with Alert Box in WebDriver in Selenium How To Resolve UnhandledAlertException  While working with Alert Box in WebDriver in Selenium Reviewed by Animesh Chatterjee on December 11, 2014 Rating: 5

How to Resolve SocketException In Selenium for Internet Explorer and Chrome

November 24, 2014
Many a times we get the below written Socket exception in Selenium. I am giving a sample stack trace.It happens mostly with IE and Chrome.


Listening on port 36550
Nov 22, 2014 5:02:14 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: I/O exception (java.net.SocketException) caught when processing request: Software caused connection abort: recv failed
Nov 22, 2014 5:02:14 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: Retrying request
Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: Unable to get browser (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 16 milliseconds
Build info: version: '2.41.0', revision: '3192d8a', time: '2014-03-27 17:18:15'
System info: host: 'LQA1008', ip: '192.168.1.104', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0_55'
Session ID: 06ab6b34-1bd4-4ee6-979c-76e4fc741458

The issue is Session could not find the URL triggered using the method driver.get("") due to initial proxy URL (Ex: http://localhost/portNumber).
so we need to use driver.get method in a different manner. How lets see in the below section:
File file =new File("C:\\Users\\Susanth\\lib\\IEDriverServer64.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
DesiredCapabilities cap= new DesiredCapabilities();
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
cap.setCapability("initialBrowserUrl", URL);    
cap.setJavascriptEnabled(true);
driver=new InternetExplorerDriver(cap);

Also if you don't want to use INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS , then check this blog-http://jimevansmusic.blogspot.com/2012/08/youre-doing-it-wrong-protected-mode-and.html?m=1
How to Resolve SocketException In Selenium for Internet Explorer and Chrome How to Resolve SocketException In Selenium for Internet Explorer and Chrome Reviewed by Animesh Chatterjee on November 24, 2014 Rating: 5

Page Object Pattern Major Drawback in Selenium- A nice Video to watch

February 03, 2014
This is a nice video, I have found in youtube.it describes the biggest drawback about Page Object pattern of Selenium..

Page Object Pattern Major Drawback in Selenium- A nice Video to watch Page Object Pattern Major Drawback in Selenium- A nice Video to watch Reviewed by Animesh Chatterjee on February 03, 2014 Rating: 5

How To Resolve IllegalStateException for IEdriver in Selenium

February 03, 2014
This is a very common problem and I found the solution while doing a preliminary checklist.

Well, this problem occurred when my friend tried to execute his first selenium script with IE.

As per code concern he has used..


System.setProperty("webdriver.ie.driver","C:\\Perl64\\bin\\IEDriverServer" );
InternetExplorerDriver d3 = new InternetExplorerDriver();
d3.get(http://gmail.com);


With this he got the below written exception..


Exception in thread "main" java.lang
.IllegalStateException: The driver executable does not exist: C:\Perl64\bin\IEDriverServer
at com.google.common.base.Preconditions.checkState(Preconditions.java:177)
at org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:117
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:112)


Its complaining that the IEDriver does not exist  "The driver executable does not exist: C:\Perl64\bin\IEDriverServer"

Now question is how to solve this problem, well..while doing a preliminary check list I found the basic problem i.e like most of us he forgot to add .exe in the driver.  i.e.--

System.setProperty("webdriver.ie.driver","C:\\Perl64\\bin\\IEDriverServer.exe" );
InternetExplorerDriver d3 = new InternetExplorerDriver();
d3.get(http://gmail.com);


This code worked fine.
How To Resolve IllegalStateException for IEdriver in Selenium How To Resolve IllegalStateException for IEdriver in Selenium Reviewed by Animesh Chatterjee on February 03, 2014 Rating: 5

How To Avoid Selenium Crash While Sending A Huge Text Using SendKeys?

January 27, 2014
sendkey is a very useful and most frequently used command while developing test through java and Selenium.
But recently I have seen Selenium viz underlying browser [like-Mozilla Fireox mainly] hangs when I try to send more than 1000 characters.

let us assume I have a note to process.There is a textarea in the application which will accept 2500 characters. Now the code I have tried..


WebElement test = driver.findElement(By.id(TXT_APPT_NOTES));
test.sendKeys(ApptNotes);


if the ApptNotes is more than 1000 character , selenium viz Mozilla Firefox hangs.
So what could be a good solution--
Well there is something called clipboard Which is capable of storing huge text or information.I came across a nice post from java practices[http://www.javapractices.com/topic/TopicAction.do?Id=82]. This gave me an instant idea about how to overcome this problem.

We have to code accordingly and need to use this nice feature..


let me go step by step...


import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;

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


public class TextTransfer  implements ClipboardOwner{

 public static void main(String[] args) {
  TextTransfer textTransfer = new TextTransfer();
  WebDriver driver=new FirefoxDriver(); 
  Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
  //Copying huge chunk of code to clipboard
  WebElement test = driver.findElement(By.id(TXT_APPT_NOTES));
  textTransfer.setClipboardContents(test.getText().toString());
  
   }

 private void setClipboardContents(String text2Copy) {
  // TODO Auto-generated method stub
   StringSelection stringSelection = new StringSelection(text2Copy);
  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
     clipboard.setContents(stringSelection, this);
  
 }

 @Override
 public void lostOwnership(Clipboard arg0, Transferable arg1) {
  // TODO Auto-generated method stub
  
 }
}
This code will copy the huge text into clipboard.
Now getting text from clipboard is having two ways..

use sendkeys and without using sendkeys

Using sendKeys function.
say I want to set it to a webElement
WebElement test = driver.findElement(By.id(TXT_APPT_NOTES_2));
test.sendKeys(ctrl+v)

The second approach where we will not use the sendkeys..


public String getClipboardContents() {
      String result = "";
      Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
      //odd: the Object param of getContents is not currently used
      Transferable contents = clipboard.getContents(null);
      boolean hasTransferableText =
        (contents != null) &&
        contents.isDataFlavorSupported(DataFlavor.stringFlavor)
      ;
      if (hasTransferableText) {
        try {
          result = (String)contents.getTransferData(DataFlavor.stringFlavor);
        }
        catch (Exception ex){
          System.out.println(ex);
          ex.printStackTrace();
        }
      }
      return result;
    }
The entire code will be like below:

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;

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


public class TextTransfer  implements ClipboardOwner{

 public static void main(String[] args) {
  TextTransfer textTransfer = new TextTransfer();
  WebDriver driver=new FirefoxDriver(); 
  Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
  //Copying huge chunk of code to clipboard
  WebElement test = driver.findElement(By.id(TXT_APPT_NOTES));
  textTransfer.setClipboardContents(test.getText().toString());
  //getting the huge text from clipboard
  String getClipboardText=textTransfer.getClipboardContents();
   }

 private void setClipboardContents(String text2Copy) {
  // TODO Auto-generated method stub
   StringSelection stringSelection = new StringSelection(text2Copy);
  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
     clipboard.setContents(stringSelection, this);
  
 }

 @Override
 public void lostOwnership(Clipboard arg0, Transferable arg1) {
  // TODO Auto-generated method stub
  
 }
  public String getClipboardContents() {
      String result = "";
      Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
      //odd: the Object param of getContents is not currently used
      Transferable contents = clipboard.getContents(null);
      boolean hasTransferableText =
        (contents != null) &&
        contents.isDataFlavorSupported(DataFlavor.stringFlavor)
      ;
      if (hasTransferableText) {
        try {
          result = (String)contents.getTransferData(DataFlavor.stringFlavor);
        }
        catch (Exception ex){
          System.out.println(ex);
          ex.printStackTrace();
        }
      }
      return result;
    }

}
hope that helps!!

How To Avoid Selenium Crash While Sending A Huge Text Using SendKeys? How To Avoid Selenium Crash While Sending A Huge Text Using SendKeys? Reviewed by Animesh Chatterjee on January 27, 2014 Rating: 5

Why Xpath Is Slower in Browsers Specially In Internet Explorer?

January 26, 2014
This question is asked in a forum. All most all the selenium developers try to avoid to use xpath. They use only in one condition if at tall they don't find any other locator correctly.
I was reading articles on this, and I found

I request all of you to go through these links.
So it is not good to blame xpath. It is the version of the browsers and how they are rendering the Xpath.The report clearly shows that IE-9 onwords xpath is not that slow.The performance difference is slightly in favor of CSS for non-IE browsers and slightly in favor of XPath for IE browsers.
I got one more example where xpath performed slow:



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

public class qtpseleium_example {

 public static void main(String[] args) throws Exception {
  WebDriver driver=new FirefoxDriver();
  driver.get("http://qtpselenium.com/"); 
  driver.manage().window().maximize();
  driver.findElement(By.xpath("//*[@src='http://qtpselenium.com/images/MemberLogin_Button_R.jpg']")).click();
  driver.findElement(By.xpath("//a[@href='http://qtpselenium.com/login/seleniumLogin.php']/img")).click(); 
  driver.findElement(By.xpath("//input[@name='email1']")).sendKeys("subhasis.bhatt@xxxx");
  driver.findElement(By.xpath("//input[@name='password']")).sendKeys("xxxx");
  driver.findElement(By.xpath("//input[@type='submit']")).click();
  Thread.sleep(10000);
  //driver.findElement(By.xpath("//div[@class='box1']/ul/li[2]/a[contains(text(),'Selenium Training')]")).click();
  driver.findElement(By.xpath("//a[contains(@href,'selenium/module11')]/img")).click();
  driver.findElement(By.xpath("//a[text() = 'Part1']")).click();
  //doesn't work--String text=driver.findElement(By.xpath("//a[contains(text(),'Part 1')]")).click();
  //doesn't work--String text=driver.findElement(By.xpath("//a[contains(@onclick,'module11_1.php')]")).click();
  //doesn't work--String text=driver.findElement(By.xpath("//body[a[position()=1 and contains(text(),'Part 1')]]")).click();

 }

}

But when it was executed it gave:
ERROR:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//a[text() = 'Part1']"}
Command duration or timeout: 170 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.46.0', revision: '87c69e2', time: '2015-06-04 16:17:10'
System info: host: 'BUBU', ip: '10.0.0.5', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_45'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=39.0, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: c15688ec-f6d8-4cb2-b3bd-b5ecc29f2094
*** Element info: {Using=xpath, value=//a[text() = 'Part1']}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:605)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:358)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:455)
at org.openqa.selenium.By$ByXPath.findElement(By.java:358)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:350)
at Module13.qtpseleium_example.main(qtpseleium_example.java:22)
Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//a[text() = 'Part1']"}
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.46.0', revision: '87c69e2', time: '2015-06-04 16:17:10'
System info: host: 'BUBU', ip: '10.0.0.5', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_45'
Driver info: driver.version: unknown
at .FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/SUBHAS~1/AppData/Local/Temp/anonymous2877297415601679170webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:10299)
at .FirefoxDriver.prototype.findElement(file:///C:/Users/SUBHAS~1/AppData/Local/Temp/anonymous2877297415601679170webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:10308)
at .DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/SUBHAS~1/AppData/Local/Temp/anonymous2877297415601679170webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12282)
at .DelayedCommand.prototype.executeInternal_(file:///C:/Users/SUBHAS~1/AppData/Local/Temp/anonymous2877297415601679170webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12287)
at .DelayedCommand.prototype.execute/<(file:///C:/Users/SUBHAS~1/AppData/Local/Temp/anonymous2877297415601679170webdriver-profile/extensions/fxdriver@googlecode.com/components/command-processor.js:12229) error.





Now when we put more wait between lines

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

public class qtpseleium_example {

 public static void main(String[] args) throws Exception {
  WebDriver driver=new FirefoxDriver();
  driver.get("http://qtpselenium.com/"); 
  driver.manage().window().maximize();
  driver.findElement(By.xpath("//*[@src='http://qtpselenium.com/images/MemberLogin_Button_R.jpg']")).click();
  Thread.sleep(5000);
  driver.findElement(By.xpath("//a[@href='http://qtpselenium.com/login/seleniumLogin.php']/img")).click();
  Thread.sleep(5000);
  driver.findElement(By.xpath("//input[@name='email1']")).sendKeys("subhasis.bhatt@xxxx");
  driver.findElement(By.xpath("//input[@name='password']")).sendKeys("xxxx");
  driver.findElement(By.xpath("//input[@type='submit']")).click();
  Thread.sleep(5000);
  //driver.findElement(By.xpath("//div[@class='box1']/ul/li[2]/a[contains(text(),'Selenium Training')]")).click();
  Thread.sleep(5000);
  driver.findElement(By.xpath("//a[contains(@href,'selenium/module11')]/img")).click();
  Thread.sleep(5000);
  driver.findElement(By.xpath("//a[text() = 'Part1']")).click();
  Thread.sleep(5000);
  String text=driver.findElement(By.xpath("//a[contains(text(),'Part 1')]")).click();
  Thread.sleep(5000);
  String text=driver.findElement(By.xpath("//a[contains(@onclick,'module11_1.php')]")).click();
  Thread.sleep(5000);
  String text=driver.findElement(By.xpath("//body[a[position()=1 and contains(text(),'Part 1')]]")).click();

 }

}


It started working. So it is a proof that xpath worked when given more time.
Why Xpath Is Slower in Browsers Specially In Internet Explorer? Why Xpath Is Slower in Browsers Specially In Internet Explorer? Reviewed by Animesh Chatterjee on January 26, 2014 Rating: 5

How to handle Windows Security Pop-Up Window In Different Browsers

January 26, 2014
Handling JavaScript popup using selenium webdriver is relatively easy. But handling of a pop up becomes tough if the browser uses windows authentication dialog box. Well, how the windows authentication looks like-I have given them below:
Windows Authentication
It will not have anything.I mean you can not really inspect them using firebug or inspector. Mostly if an underlying application uses windows authentication, It will look like this through Mozilla or Internet Explorer browser. Most importantly this is modal dialog box. Hence we can not avoid this. Now Webdriver supports browser level identification not windows level. So net on net we can not automate this using selenium.

By the time selenium comes with some solution let me write all possible way i tried..
Before I go deep into this let us understand different pop ups available in an application. They are as follows:

1. HTML pop-up
2. JavaScrip pop-up
3. Win32 pop-up
4. Modal pop-up
5. File upload pop-up
6. File download pop-up  

For more details please visit this blog

So HTML pop-up and JavaScrip pop-up can be handled by Selenium itself. Problem starts third points on words.
Initial days I tried with robot class as all most all the forum talked about this solution. i.e Robot class.
Robot robot  = new Robot();
robot.sendKeys(userName);
robot.keyPress(KeyEvent.VK_TAB); 
robot.sendKeys(password);
robot.keyPress(KeyEvent.VK_TAB); 
robot.keyPress(KeyEvent.VK_ENTER); 

but it is not working flawlessly. I tried By adding user id and password before start of url<
http://usename:password@websitename.com
But quickly I understand that this is a security issue. No browser will support that for long.As a result this was not my code to work with security popup.
Then one fine morning I found out a stack overflow thread. That was indicating some tool called AutoIT. The tool seemed to be very user friendly and easy to use.The code looks like-
WinWaitActive("","Authentication Required","120")
 If WinExists("","Authentication Required") Then
 Send("username{TAB}")
 Send("password{Enter}")
 EndIf

After creating this code I had to save this as an executable file like authentication.exe. Then used the below code to execute the executable file.
Runtime.getRuntime().exec("D://authentication.exe");
or one more solution was-
WinWaitActive(“Windows Security”)
ControlSetText(“Windows Security”,””,”Edit1″,”user”)
ControlSetText(“Windows Security”,””,”Edit2″,”pass”)
//Click Ok/Login button
Send(“{ENTER}”)
Problem solved!! I was very happy to use this solution. It was running nice for Internet Explorer and Firefox browser. But when I thought everything was over , Chrome came up with unique problem.
The same popup came in a form based authentication form.


something like the image. Most importantly this was modal dialog box.This was appearing as an extra security after giving user name and password and click on sign in.Since this was modal dialog box WebDriver click control was getting trapped inside. It was  not executing next statement.
So if the browser was chrome it was not possible to switch to alert and put all values. AutoIT failed to identify the alert itself. To add more pain this authentication may come 2-3 times even more than that.
So I had to find some other solution.
I found sikuli then,a free image based little week but steady solution.
Process was very simple.Added the sekuli jar to the classpath.
I created the images as per sikuli editor.




And the sample prototype code was-
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.sikuli.script.*;

public class ChromePrototype {

 public static void main(String[] args) throws InterruptedException, IOException, FindFailed {
  // TODO Auto-generated method stub
   System.setProperty("webdriver.chrome.driver", "D:\\SeleniumT\\ChromePrototype\\chromedriver.exe");
   System.out.println("start1");
  WebDriver driver ;

  ChromeOptions options = new ChromeOptions();
  options.addArguments("--start-maximized");
  driver = new ChromeDriver( options );
  driver.get("myURL");
  
  driver.findElement(By.name("ai")).sendKeys("someValue");
  driver.findElement(By.name("un")).sendKeys("UserName");
  driver.findElement(By.name("pd")).sendKeys("Password");
   System.out.println("start2");
   Pattern floginButton = new Pattern("D:\\imagebase\\fLogin.png");
   Screen screen = new Screen();
   screen.click(floginButton);
   Thread.sleep(1000);

   Pattern userName = new Pattern("D:\\imagebase\\UserName.png");
   Pattern authentication = new Pattern("D:\\imagebase\\Authenticati.png");
   
   do{
    LogIn();
    Thread.sleep(1000);
   }
   while(screen.exists(authentication) != null);
  

  
 }
 
 
 
 public static void  LogIn() throws FindFailed, InterruptedException
 {
  
  
   Screen screen1 = new Screen();
   
   Pattern userName = new Pattern("D:\\imagebase\\UserName.png");
  // screen.wait(userName, 10);
   screen1.click(userName);
   screen1.type("instant");
   Thread.sleep(1000);
   Pattern password = new Pattern("D:\\imagebase\\Password-1.png");
  // screen.wait(password, 10);
  screen1.click(password);
   screen1.type("password");
   Pattern secondlogin = new Pattern("D:\\imagebase\\secondlogin.png");
   screen1.click(secondlogin);
   screen1=null;
   Thread.sleep(1000);
 }

 
   
}

It worked. Since the first click is originated from sikuli so webdriver click trapping was resolved.I will update this page if I get better solution But till then. Sikuli did my job!!!.


How to handle Windows Security Pop-Up Window In Different Browsers How to handle Windows Security Pop-Up Window In Different Browsers Reviewed by Animesh Chatterjee on January 26, 2014 Rating: 5

How To Open Multiple Instances Of Different Browsers Through Selenium

January 12, 2014
Testing websites through selenium is a hotcake now days. It is also equally important to check how the site looks like in different browsers. Till date the process of such checking were sequential.like first set the target as IE browser then check and again set the target as Chrome and then Firefox etc The advancement in technology made the possibilities to check them in parallel. For such thing we don't need to  change our testing approach in a big way. It is only change in the starting of the test.

We need to start 3/4 browsers at the beginning of each test. This post will show how to open 3/4 browsers and 3/4 instance of each browsers at the beginning of the test.It is all about a command to open such possibilities.


java -Dwebdriver.chrome.driver=C:\jar\chromedriver.exe 
-Dwebdriver.ie.driver=C:\jar\IEDriverServer.exe 
-jar selenium-server-standalone-2.38.0.jar -role node 
-hub http://169.254.61.93:4444/grid/register -port 5556 
-browser browserName=firefox,maxInstances=4 
-browser browserName=chrome,maxInstances=4 
-browser browserName=iexplorer,maxInstances=4 
-browser browserName=safari,maxInstances=4 -maxSession 6

Now the things you require..

  • Chrome driver
  • IE driver
  • Firefox driver
[32/64 bit depending on your test machine configuration]

you need to provide the correct path for the same.
hope that helps!!
How To Open Multiple Instances Of Different Browsers Through Selenium How To Open Multiple Instances Of Different Browsers Through Selenium Reviewed by Animesh Chatterjee on January 12, 2014 Rating: 5

How To Search Using Google and Click on a Specific Link Using Selenium?

December 25, 2013
To start with selenium learning, the first step I suggest is to automate google. In this exercise i will try to show how to automate google.

The objective of this post is to automate a flow where steps are--

  1. open a firefox browser 
  2. Navigate to google. 
  3. in the search box type askqtp. 
  4. Click on search
  5. list the links available in the search
  6. Click on the first link
  7. Read the title. 
for this

//Normal imports
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.firefox.FirefoxDriver;


public class ClickaLink {

public static void main(String[] args) {
//Creating the web driver
WebDriver fd=new FirefoxDriver();
//Step 1&2
fd.get("http:\\google.com");
fd.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
//Step-3
fd.findElement(By.xpath("//input[@class='gbqfif']")).sendKeys("askqtp");
//step-4
fd.findElement(By.xpath("//*[@id='gbqfb']")).click();
WebElement box=fd.findElement(By.xpath("//*[@id='res']"));
//the center box in the results page that has all the links Step-5
List<WebElement>allLinks=box.findElements(By.xpath("//*[@id='rso']/li/div/h3/a"));
//xpath of the links displayed

System.out.println("Total Links -->"  allLinks.size());
for(int i=1;i<allLinks.size();i++  ){
System.out.println(allLinks.get(i).getText());
//Step-6
allLinks.get(1).click();
//click on the first link that is displayed
}
}


By this code you will be able to click on the firstlink and automate google search. Hope this helps.

How To Search Using Google and Click on a Specific Link Using Selenium? How To Search Using Google and Click on a Specific Link Using Selenium? Reviewed by Animesh Chatterjee on December 25, 2013 Rating: 5

What is the defference between driver.navigate().refresh() and pressing F5?

December 22, 2013
I was going through a forum and found one of my mate tried to refresh a page after doing some operation in web. He used..
driver.findElement(By.xpath("//body")).sendKeys(Keys.F5);


But this code was failing while running the code. I was googling for a suggestion or help and finally found one solution in stackoverflow..

Being interested , I observed all the possible causes and agreed the discussion there. The summary I found is as below:
It's not exactly equivalent to pressing F5 though. driver.navigate().refresh() in its request header says "no-cache" and, as a result, unconditionally reloads all content. Whereas pressing F5 could result in a "If-Modified-Since" request, that could get a "304 Not Modified" response.
Wow that is what I was looking for. Since this page is based on ajax so F5 was not working there. When I have used
driver.navigate().refresh();


It worked like a boom.
Also for pressing F5, we have one more option..

Actions actionObject = new Actions(driver);
actionObject.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();


Hope that helps.
What is the defference between driver.navigate().refresh() and pressing F5? What is the defference between driver.navigate().refresh()  and pressing F5? Reviewed by Animesh Chatterjee on December 22, 2013 Rating: 5

Alternative Approach to Solve Thread.Sleep in Java or Selenium or in OpenScript

December 22, 2013
Now a days if we want our execution to be halted for sometimes [mainly observed in Automation Testing when a page needs to be loaded first and then some line of code will be executed], We use Thread.sleep(int Sec) method. Well this is quite recognized/common method to solve if we want my program to wait for specific point of time.More details can be found here in java doc.
As per java doc..
Notice that main declares that it throws InterruptedException. This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException.


But now a days I have seen that it is a requirement to do more customization regarding the same.
One approach can be --[taken from stackoverflow]

public static void pause(int seconds){
     Date start = new Date();
     Date end = new Date();
     while(end.getTime() - start.getTime() < seconds * 1000){
         end = new Date();
     }
 }

Another Approach can be to use.
Pause.pause(int sec)

 The third approach can be..
public static void wait_for_element(){
     do
            {
      pause(2);//use the first approach for implementing this pause method
            }
     until(driver.findElements(By.xpath("//*[starts-with(@id,'frm')]")).get(1).isDisplayed())
//the element is displayed
   

Now the choice is yours ...depending on the scenario, you can take any one of the process. Happy testing.

Alternative Approach to Solve Thread.Sleep in Java or Selenium or in OpenScript Alternative Approach to Solve Thread.Sleep in Java or Selenium or in OpenScript Reviewed by Animesh Chatterjee on December 22, 2013 Rating: 5

Object Repository Concept In Selenium .

December 01, 2013
Object repository is place where we store all information related to an object. Typically in Quick Test Professional it is an optional part.[Descriptive programming]. But we use it regularly. We depend on QTP to identify object during run time and play back time.
The below written posts you help you to get more details about the same:



But when it comes to selenium there are way to store Object's properties.
In selenium we generally store the xpath or relative paths or locator information.

usrname_txt=//*[@id='username']
passwd_txt=//*[@id='passwd']


The ways you can store these are..

  • Excel--Here you need POI jar to read and write
  • Notepad/CSV--File operation in java
  • XML--File operation
  • Class page wise
  • Using Inner class[Nested class concept]
Excel will typically Look like-

LogicalName
PropertyType
Propertyvalue
!Yahoo Home Page
usrname_txt
xpath
//*[@id='username']
passwd_txt
xpath
//*[@id='passwd']

 XML format

!Yahoo Home Page
<Object name> usrname_txt <Property type> xpath < Property  Value>//*[@id='username']
<Object name> findppl_txt <Property type> classname < Property  value> searchIconBorder

Notepad format--
username,xpath,//*[@id='username']
password,xpath,//*[@id='passwd']

Class Page Wise
Class LoginPage{
     String userName=By.xpath(//*[@id='username'])
     String password=by.xpath(//*[@id='passwd'])
     .......
    ........
}
But these are ok when you are a learner or your test is significantly low in size or time. These methods are not effective when your test is very big in nature or say test will be running for 3 days or 4 days.Also they need either a 3rd party jar like-POI or java's file handling operation which are not great for architecture point of view when time is a constraint.

So What could be the solution..
I would prefer the inbuilt nested class structure approach should be taken when your test is really big.

let me explain how..


public static class LoginPage{
private static class Login{
String userName=By.xpath(//*[@id='username'])
String password=by.xpath(//*[@id='passwd'])
}
private static class bodyElement{
.......
........
}

}


Well the advantages for this approach are--

  • Since they are static they will be loaded when you are trying to run login class. 
  • All objects will be available in Primary memory so no delay in execution of the test.
  • Readability will be easy but your test will remain huge
  • Less dependency on the external jars so delay in getting the data.
  • your primary memory will be free from the unwanted code.
  • Let JVM decide which objects and data will present on the memory  instead of us!!!
  • Garbage collection will be effectively fast.[Note we do not have any control on that programming] so helping GC by reducing load will be good from architecture point of view.
Object Repository Concept In Selenium . Object Repository Concept In Selenium . Reviewed by Animesh Chatterjee on December 01, 2013 Rating: 5

What Is Desired Capabilities in Selenium??

September 10, 2013
Desired Capabilities got introduced in Selenium to work with lot of browser capabilities. Mostly like-profile data,handling browser cookies , SSL security popup file upload/save etc. In an easy line-It is used to specify the desired capability mostly related to session before the session gets created. In a layman's language, it is few set of properties/flags/options that needs to be set before we start our test run.

While designing the test it is specified in Webdriver so the client receive the desired capabilities where the run needs to be initiated. If the server sends no data then no capabilities have been supported.

More on webdriver capabilities can be found here. Google's doc is also very helpful in this respect. More can be found here as well.

The most interesting aspect of desired capabilities is , it gives birth the concept of exception handling.The food for thought can be found here.

If we go little details , this class helps us to communicate with webdriver like which environment we will be running our test scripts. Basically helps us to configure webDriver.It is not only applicable for browser, it is also applicable for mobile testing,where we can set the device properties along with browser version.If we want to run test cases on a different browser on different O.S.

Below are the different methods supported by Desired Capability Class:

Method Names Syntax Description
getBrowserName public java.lang.String getBrowserName()Gets the current Browser Name
setBrowserName public void setBrowserName(java.lang.String browserName)Sets the current Browser Name(java.lang.String browserName)
getVersion public java.lang.string getVersion()Gets the browser version
setVersion public void setVersion(java.lang.String browserVersion)Sets the version to the current browser
getPlatform public Platform getPlatform()Gets the current platform information
setPlatform public Platform setPlatform()Sets the platform
getCapability public java.lang.object getCapability(java.lang.String CapabilityName)Use to get the current capability of the system
setCapability public void setCapability(java.lang.String capabilityName ,boolean value)Use to set the current capability of the system
setCapability public void setCapability(java.lang.String capabilityName ,java.lang.String.value)sets the current capability with a given string
setCapability public void setCapability(java.lang.String capabilityName ,PlatformValue)sets the current capability with a given Platform info
setCapability public void setCapability(java.lang.String capabilityName ,java.lang.Object.value)sets the current capability with a given object

Sample Implementations:

import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class DesiredCapability {

public static void main(String[] args) {

DesiredCapabilities cap=DesiredCapabilities.internetExplorer();
cap.setCapability(CapabilityType.BROWSER_NAME, "IE");
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
cap.setPlatform(Platform.WIN8);
System.setProperty("Webdriver.ie.driver","C:\\test\\IEDriverServer.exe");
WebDriver driver=new InternetExplorerDriver(cap);
driver.get("www.google.com");
}

}
Few more capabilities:

Method Names Syntax Description
acceptSslCerts CapabilityType.Accept_SSL_CERTSThis is used to enable or disable browser session to accept or reject the SSL certificates
applicationCacheEnabled CapabilityType.SUPPORTS_APPLICATION_CACHEEnables browsers to use cache
CssSelectorEnabled CapabilityType.SUPPORTS_FINDING_BY_CSSChecks if the CSS selector is enabled for finding web element
javaScriptEnabled CapabilityType.SUPPORTS_JAVASCRIPTChecks if the javascript execution is enabled for the browser
TakesScreenshot CapabilityType.TAKES_SCREENSHOTChecks if screenshot taking ability is enabled or not
WebStorage Enabled CapabilityType.SUPPORTS_WEB_STORAGEChecks if the browser instance can interact with storage object
HandleAlerts CapabilityType.SUPPORTS_ALERTSChecks if the browser instance can handle window popup.

One good example of Desired capability is to disable the save password popup in Chrome. How that is done?

ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-save-password-bubble");
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("credentials_enable_service", false);
prefs.put("profile.password_manager_enabled", false);
options.setExperimentalOption("prefs", prefs);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

What Is Desired Capabilities in Selenium?? What Is Desired Capabilities in Selenium?? Reviewed by Animesh Chatterjee on September 10, 2013 Rating: 5
Powered by Blogger.