Monday, November 4, 2013

All about accessing check boxes using web driver

In all my previous examples we checked how we can extract, Locate and input data for various web input types. In this example lets see about the "Check Boxes". How we can locate, Print  the values, get the count ect.. Below code has different aspects of how we can access check boxes. 

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class Test3 {
public static void main(String[] args) throws Exception {
//Locate the element and gets the check boxes count 
WebDriver A = new FirefoxDriver();
A.get("http://www.echoecho.com/htmlforms09.htm");
List<WebElement> B = A.findElements(By.xpath("//table[3]/tbody/tr/td/table/tbody/tr/td/input"));
int count = B.size();
System.out.println(count);
//Prints the values inside the check box
for (int i = 0; i <count; i++) {
System.out.println(B.get(i).getAttribute("Value"));
   }
//Clicking on each check box in a loop 
for (int j = 0; j < count; j++) {
B.get(j).click();
System.out.println("Clicked On"+ B.get(j).getAttribute("Value"));
     }

//Checks if the values are clicked already 
for (int k = 0; k < count; k++) {
if (B.get(k).getAttribute("checked") != null)
System.out.println(B.get(k).getAttribute("value")+"--- Is Cecked");
else 
System.out.println(B.get(k).getAttribute("value")+"---Is not checked"); 
  }


//Reset the check boxes unchecked status if they are already clicked
for (int u = 0; u < count; u++) {
if (B.get(u).getAttribute("checked") != null)
B.get(u).click();} 
System.out.println("After Reseting");

//Check initially if values are checked or not in a loop 
for (int k = 0; k < count; k++) {
if (B.get(k).getAttribute("checked") != null)
System.out.println(B.get(k).getAttribute("value")+"--- Is Cecked");
else 
System.out.println(B.get(k).getAttribute("value")+"---Is not checked");                                                                                     }


}

}

The output of this program is 

3

Milk
Butter
Cheese

Clicked OnMilk
Clicked OnButter
Clicked OnCheese

Milk--- Is Cecked
Butter---Is not checked
Cheese--- Is Cecked

After Reseting
Milk---Is not checked
Butter---Is not checked
Cheese---Is not checked

Read a PDF file with OCR

So far in all the previous examples we check how we can read the string or any type of a data on an image. Now lets see how we can read a PDF file with the use of OCR class methods. 

to start off you can create a simple PDF file with sample texts in it (Many pages as you want) or simply download any PDF file. In my example i have created a pdf file with 03 pages and below text on each page 

Page 01 
Page 02 
Page 03 

now below code will read the PDF file and will print the data inside of it.

import java.awt.image.BufferedImage;  
import java.io.File;   
import com.asprise.util.ocr.OCR;  
import com.asprise.util.pdf.PDFReader;
public class Test2 { 
public static void main(String[] args) throws Exception {

//Creates a new object from OCR class 
OCR ocr = new OCR();

//Creates a new object from PDFReader class and assign the PDF file location 
PDFReader reader = new PDFReader(new File("D:\\1.pdf"));

//Open the PDF file 
reader.open();

//Assign the number of pages in the PDF file to a int variable 
int pages = reader.getNumberOfPages();

//Prints the number of pages in the PDF file 
System.out.println("Number of pages are "+pages);

//Read the contents inside the PDF file in a loop and prints the contents 
for(int i=0; i<pages; i++) {
BufferedImage image = reader.getPageAsImage(i);
System.out.println("OCR result:\n" + ocr.recognizeEverything(image));                             }

//Close the PDF file 
reader.close();
   
 }

}


The output of this file is 

Number of pages are :  3

OCR result:

^UNLICENSED VERSlON FOR EVALUATlON PURPOSE ONLY. Asprise Java PDF Libray - http:llasp
Page 01

OCR result:
^UNLICENSED VERSlON FOR EVALUATlON PURPOSE ONLY. Asprise Java PDF Libray - http:llasp
Page OZ

OCR result:
^UNLICENSED VERSlON FOR EVALUATlON PURPOSE ONLY. Asprise Java PDF Libray - http:llasp
Page 03


Read a Bar code from WebDriver

In my previous post i have shown you how we can read a test on an image either in a web site location or in your hard drive. Using the same techniques lets see how we can read a bar code with "OCR" class.  But this time we have to use a special method, and that is "OCR().recognizeBarcode()". Lets see how we can do this. 

below is the bar code image that i'm going to read from my HD


Simply download this image and save it in your HD and run below code. Make sure to change the image path according to your image location. 

import java.awt.image.BufferedImage;  
import java.awt.image.RenderedImage;  
import java.io.File;  
import javax.imageio.ImageIO;  
import com.asprise.util.ocr.OCR;  

public class Test2 { 
public static void main(String[] args) throws Exception {

//Creates a new object and assign the image location 
BufferedImage image = ImageIO.read(new File("D:\\TEST\\Bar_code.jpg"));  

//Creates a string variable and assign the bar code values 
String s = new OCR().recognizeBarcode(image);

//Creates a string variable and assign other character values
String imageText = new OCR().recognizeCharacters((RenderedImage) image);   

//Prints the bar code values
System.out.println("Text From Image : \n"+s);    

//Prints the other character values 
System.out.println("Text From Image : \n"+ imageText);    

//Prints the length of the texts  
System.out.println("Length of total text : \n"+ imageText.length());     
 
 
}


}


The output of the program is : 

Text From Image : 
123456789012
Text From Image : 

Asprise OCR
Speed. Accuracy.

Length of total text : 

33


Read an image from your HD & read the text on it

In my previous example i have shows you how can we read an image on the web page and prints the text on it. Now lets see how we can read an image which is in your hard driver and prints the texts on it .

same as previous blog post m using the same "OCR" class but with different methods. Just copy and paste this code and try your self. But make sure you have a file in "D:\\TEST\\123.jpg" this location or you can just change the file location to where ever you want :) 


import java.awt.image.BufferedImage;  
import java.awt.image.RenderedImage;  
import java.io.File;  
import javax.imageio.ImageIO;  
import com.asprise.util.ocr.OCR;  

public class Test2 {
//Read text values on an image 
public static void main(String[] args) throws Exception {

//Create a new object from BufferImage class and assign the image location
BufferedImage image = ImageIO.read(new File("D:\\TEST\\123.jpg"));

//Read the image characters      
String imageText = new OCR().recognizeCharacters((RenderedImage) image);    

//Prints the image text 
System.out.println("Text From Image : \n"+ imageText); 

//Prints the length of the text   
System.out.println("Length of total text : \n"+ imageText.length());     
  
}

}

My actual image is 


And the code output is 


Text From Image : 
ABCDEFG

Length of total text : 
9

now you can try this code with your images to see the result. Do read my next blog post to see how we can read a bar code with this. 

Sunday, November 3, 2013

Read the text on an Image

Sometimes in web applications we come across with pages which are loaded with images with text on it. In these scenarios we cannot read the text inside the image with the normal Xpath selectors. Xpath will only help to locate where the image is actually. So to sort out this scenario we have a special class in java called  OCR (Optical Character Recognition) which does the work for us. 

To start off with OCR first you need to follow some steps. 
  1. Download "Asprise OCR" libraries , depending on the operating system you are using .
  2. Unzip the downloaded  folder and add the "aspriseOCR.jar" file to your working directory . If you want you can download the single jar file from here.
  3. Set the path in environments variables My Computer --> Properties --> Advanced system settings --> environment Variables --> Create a new system variable as below.

   4. And now you are good to go 

Look at below image 



now you can just get this same code and try your self 

import java.awt.Image;  
import java.awt.image.BufferedImage;  
import java.awt.image.RenderedImage;  
import java.io.File;  
import java.io.IOException;  
import java.net.URL;  
import javax.imageio.ImageIO;  
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.firefox.FirefoxDriver;  
import org.testng.annotations.BeforeTest;  
import org.testng.annotations.Test;  
import com.asprise.util.ocr.OCR;  

public class Test2 {
//Read text values on an image 
public static void main(String[] args) throws Exception {
//Creates an object from WebDriver 
WebDriver driver = new FirefoxDriver();
//Calls the URL
driver.get("http://anjiztechshare.blogspot.com/2013/11/read-text-on-image.html");  
 
//Locate the image and get the image scr attribute values and assigns to a variable 
String imageUrl=driver.findElement(By.xpath("//*[@id='post-body-8001467531740453328']/div[4]/div[7]/a/img")).getAttribute("src"); 
//Prints the assigned variable values 
System.out.println("Image source path : \n"+ imageUrl); 
 
Thread.sleep(3000);
 
//Creates a new object from URL class and pass the variable as a parameter 
URL url = new URL(imageUrl);  

//Read the URl value 
Image image = ImageIO.read(url);  
 
//Creates a String variable to assign the values read by the OCR()
String s = new OCR().recognizeCharacters((RenderedImage) image);  
//Prints the text on the image line by line 
System.out.println("Text From Image : \n"+ s);  
 
//Prints the length of the image 
System.out.println("Length of total text : \n"+ s.length());  
driver.quit(); 
 
}

}

Here is the output of the program 


Image source path : 
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEioEQTjbpO6sn0p9vr7xJupgPuYllrM6ePy8Jii8w1Qzp5B_28MJOr-quBowTghGDqCD2kCQUgQxCWB2KM0Li5FhsHZ16SqNir1L423weXHswI1Inkg_GKgxljeyAC_hyQMx0ZPTt94hpPN/s320/love.jpg


Text From Image : 
Never M2suse the O, ne
Who Likes You
Never Say Busy To Th,e One
Who Needs You
Never cheat The One
Who ReaZZy Trust You,
Never foJnget The One
Who Zways Remember You.

Length of total text : 
175

Now lets see how we can read an image from the hard drive and prints the letters in it. please read my next blog post.  Good luck for now. 






Mouse over Menus and select

jQuery is the most famous method that most of the web designers/ developers are using these days. To make the web application looks better, either make it fancy or us er friendly most of the people tend to use these. Mouse over events are one of the famous events outta jQueries. 

When accessing these types of Mouse over elements using xpath we cannot directly access them because it is triggered through an event. So we have to deal with them in different way. Below code is explaining how we can click on a sub menu which expanding on jQuery trigger.  You can simply cope and paste this code in your java tool and test your self. 

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class Test3 {
public static void main(String[] args) throws Exception {

//Creates a web driver object 
WebDriver A = new FirefoxDriver();

//Loads the URL 
A.get("http://www.johnlewis.com/"); 

//Locate the main menu and assign the xpath location to a variable 
WebElement MouseOverLink = A.findElement(By.xpath("//a[text()='Christmas']")); 

//Creates an object from Action class 
Actions Action_01 = new Actions(A); 

//perform moveToeElement() method and pass the variable value  
Action_01.moveToElement(MouseOverLink).perform(); 

//locate the Sub Menu and assign the xpath location to a variable 
WebElement MouseOverLink2 = A.findElement(By.xpath("//a[@href='/christmas/new-for-2013/c6000450511']"));

//Perform moveToeElement() method and pass the variable value  
Action_01.moveToElement(MouseOverLink2).perform();

//Click on the sub menu
Action_01.click().perform(); 


}

}

When we are dealing with the web elements the "Actions" class is very important. To learn about the methods and functions inside the "Actions" class ref below link. Read more about Actions class in java

In this example i'm using only the "moveToeElement()" method which is capable enough to move the mouse over to given element either by the xpath or a defined variable. This is very important when we have mouse over elements.  

"click().perform()" These 02 commands are same like the previous examples, Where as we can perform the click function to the given element. 


File Upload using Selenium web Driver

Another common elements that we come across in the web sites are file uploads. we can write a java script with the things that we have learnt so far to perform file upload activity. Below simple code will do the file upload. 

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

public class FileUpload{

public static void main(String[] args) throws Exception {
//Creates a WebDriver object 
WebDriver A = new FirefoxDriver();

//Goes to the site 
A.get("http://www.freepdfconvert.com/");
Thread.sleep(3000);

//Locate the file browse button and send the file name with "sendKeys() method"
A.findElement(By.xpath("//*[@id='clientUpload']")).sendKeys("D:\\1.pdf"); 
Thread.sleep(20000);

//Locate the file convert button after upload and hit click() 
A.findElement(By.xpath("//*[@id='convertButton']")).click(); 

}

}

In this example we are using the same "findElement(), sendKeys()" commands that we have used so far in previous examples. Additionally i have used "Thread.sleep(xxxx)" commands. sometimes websites might take more time to load, even to navigate from one page to another page after click, or in this scenario depending on the uploading file size it might need some time to perform. So there for i have given a wait time with "Thread.sleep(xxxx)" commands. 

You can simply copy and paste this code in your java compiler and try this out. But make sure to modify the file path in line number 12. good luck 

Friday, November 1, 2013

All about WebElement

"WebElement" is a special type of a class which comes with the selenium libraries which is capable of handling elements in the web site. All method calls will do a freshness check to ensure that the element reference is still valid. This essentially determines whether or not the element is still attached to the DOM. If this test fails, then an is thrown an exception.

Below are the most popular methods in the "WebElement" class with examples.  

Find Elements 

WebDriver A = new FirefoxDriver();
A.get("http://echoecho.com/htmlforms10.htm");

//Finds the Element 
A.findElement(By.xpath("//input[@value='Milk']")).click();
List<WebElement> B = A.findElements(By.xpath(".//td[@class='table5']//input[(@type='radio')]"));
//Gets the Size 
int count = B.size();
System.out.println(count)


Print Element Values  

//Pritns the values 
for(WebElement z : B) {
String x = z.getAttribute("value");
System.out.println(x);

      }

Clicks on the Element 

//clicks on the element 
for(WebElement z : B) {
String x = z.getAttribute("value");
z.click();

      }

Check if the element is clicked or not  

//Checks if an element is clicked or not 
for(WebElement z : B) {
String x = z.getAttribute("value");
System.out.println(z.getAttribute("value")+ "----> "+ z.isSelected());
                 }



Check if the element is enabled or not  

//Checks if an element is enabled or not 
for(WebElement z : B) {
String x = z.getAttribute("value");
System.out.println(z.getAttribute("value")+ "----> "+ z.isEnabled());
             }


Check if the element is displayed or not  

//Checks if an element is displayed or not 
for(WebElement z : B) {
String x = z.getAttribute("value");
System.out.println(z.getAttribute("value")+ "----> "+ z.isDisplayed());            }

Check location of the element 

//Gets the location of the element (If exists)
for(WebElement z : B) {
String x = z.getAttribute("value");
System.out.println(z.getAttribute("value")+ "----> "+ z.getLocation());
   }


Check location of the element 

//Gets the CSS value of the element (If exists)
for(WebElement z : B) {
String x = z.getAttribute("value");
System.out.println(z.getAttribute("value")+ "----> "+ z.getCssValue(x));
       }

Java Script Alerts

In most of the web sites now users are tend to use java scripts to perform various functions. when there are java scripts running in the web site we have to handle those elements in a different way. 

As an example if there is a window or dialog box opening upon click on click of a button we cannot locate those kinds element like we did for other. Those needs to be handled differently. Below example shows how java script enabled sites can be handled. 

//Goes to the site 
WebDriver A = new FirefoxDriver();
A.get("http://www.javascripter.net/faq/prompt.htm");
//finds the try now button and clicks
A.findElement(By.xpath("//input[@value='Try it now']")).click(); 
//Before using the method the alert class should be declared as follows 
Alert Alert01 = A.switchTo().alert(); 

//Gets alert text value (if exist)
System.out.println(Alert01.getText()); 
Alert01.sendKeys("test");  //

//Accept or Dismiss alert dialog box 
Alert01.accept(); 
Alert01.dismiss(); 
//Quit the browser 
A.quit();


Alert class provides so many various methods to handle alerts, Such as 

Alert01.accept(); 
Alert01.dismiss(); 
Alert01.getText();
Alert01.sendKeys(arg);

These functionalists  makes the testers life easier when there are so many java scripts running inside a single web application. 


Web Tables

Another concept that we commonly see in the web pages are the <table> </table>. for the user easiness and the maintainability most of the users use table tags inside the HTML codes.  When reading the data inside the tables in web driver we have a concept called "Web Tables" where we dynamically select the rows and columns directly or in a loop. 

Below set of examples will how how we can extract data from web tables in different scenarios. 

Get the count of rows in a table 
//Get the count of rows in the table
WebDriver A = new FirefoxDriver();
A.get("https://developers.google.com/bigquery/docs/sample-tables");
List<WebElement> URLS = A.findElements(By.xpath("//*[@id='gc-content']/div[1]/div/table/tbody/tr")); 
int count = URLS.size(); 
System.out.println(count); // Prints 06 rows


Get the count of columns in a table 
//Get the count of rows in the table
List<WebElement> URLS2 = A.findElements(By.xpath("//*[@id='gc-content']/div[1]/div/table/tbody/tr/td")); 
int count2 = URLS2.size();

System.out.println(count2);

Get the values inside the table to a List
//Get the values inside the table to a List 
List<WebElement> URLS = A.findElements(By.xpath("//*[@id='gc-content']/div[1]/div/table/tbody/tr"));
int count = URLS.size();
System.out.println(count);
for (int i = 0; i < URLS.size(); i++) {
System.out.println (URLS.get(i).getText()); } 


Get the specific column value 
//Print the specific column values
String Xpath1 = "//*[@id='gc-content']/div[1]/div/table/tbody/tr[";
String Xpath2 = "]/td[1]";
for (int i = 2; i <= count; i++) {
String CombineXpath = Xpath1+i+Xpath2; 
String val = A.findElement(By.xpath(CombineXpath)).getText();
System.out.println(val);          }



Print the specific row values
//Print the specific row values
String Xpath3 = "//*[@id='gc-content']/div[1]/div/table/tbody/tr[2]/td[";
String Xpath4 = "]";
for (int i = 1; i <= (count2/(count-1)); i++) {
String CombineXpath2 = Xpath3+i+Xpath4; 
String val2 = A.findElement(By.xpath(CombineXpath2)).getText();
System.out.println(val2);    }


Small calculation extracting table values 
//Do a small calculation using the contents in the web table 
String Xpath5 = "//*[@id='gc content']/div[1]/div/table/tbody/tr["; 
String Xpath6 = "]/td[3]";
double xx = 0;   
for (int i = 2; i <=3 ; i++) {
String Number_Val = A.findElement(By.xpath(Xpath5+i+Xpath6)).getText(); 
String Number_Val_Substring = Number_Val.substring(0,3); 
double Number_Val_Converted = Double.parseDouble(Number_Val_Substring); 
xx = xx + Number_Val_Converted; } 
System.out.println(xx);