Tuesday, January 10, 2012

PerlAutomation

1.1 What is Perl:
Perl referred to Practical Extraction and Report Language, Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more. Because of its strong text processing abilities, Perl has become one of the most popular languages for writing CGI scripts. Perl is an interpretive language, which makes it easy to build and test simple programs.

A typical simple use of Perl would be for extracting information from a text file and printing out a report or for converting a text file into another form.


1.2 Perl Installation:


Perl can be used either by running “ActivePerl .X.exe“installer package or by placing Perl folder itself.
1.2.1 Using ActivePerl .X.exe installer package:

Run the executable file then the below folder structure will be automatically created in our system,
Screen shot 1:




Now place “IEAutomation” and “GuiTest” folders along with “GuiTest.pm” and “IEAutomation.pm” files, under “Perl\lib\Win32”. Added to that “Win32-IEAutomation-0.5” folder should be placed under “Perl\” folder and make sure that above said “IEAutomation” and “GuiTest” folders along with “.pm” files are also present within “Win32-IEAutomation-0.5” folder. So finally our Perl folder should look like Screen shot 2.



Make sure that “IEAutomation” folder and “IEAutomation.pm” file should be move to the “Perl\Win32-IEAutomation-0.5\lib\Win32” folder and should resembles like the above folder structure.

1.3 Win32-IEAutomation-0.5:

This module tries to give web application automation using internet explorer on windows platform. It internally uses Win32::OLE to create automation object for IE.

The module allows user to interact with web page controls like links, buttons, radios, checkbox, text fields etc. It also supports frames, popup window and interaction with JavaScript dialogs like security alert, confirmation, warning dialog etc.

1.4 Perl Path Setup:

Make sure that below given paths are added into ‘PATH” environment variable.

• D:\Perl\bin;
• D:\Perl\lib;
• D:\Perl\site\bin;
• D:\Perl\Win32-IEAutomation-0.5;
• D:\Perl\Win32-IEAutomation-0.5\lib;


1.5 Perl Script Writing:

Sample Perl Script:

1.5.1 Create a scalar variable:

To create a scalar variable you must name the variable and assign it a value and then type a ";" character. If you want a text value it must be written between quotation marks. Numerical values do not need quotation marks.

For example: $name = "John Anderson"; $age = 35;

1.5.2 Create an array variable:
The difference between an array and a scalar variable is that an array can hold multiple bits of information. To create an array, type the "@" sign, the name of the array and then the values of the array within "'()" characters. Each value must be separated by commas. Text values must be written between quotation marks.

For example: @Anderson_family = ("John","Mary", "Julie", "Mark"); @ages = (35,30,7,5);


1.5.3 Create a hash variable.

Hash variables are similar to array variables except that they include a "key" and a "value." They begin with a "%" sign and are followed by the name of the variable. The values for the hash are placed within "()" and are separated by commas. However, each value in a hash consists of a key and a value.

For example: %Famly_age = ("John" => 35, "Mary" => 30, "Julie" => 7, "Mark" => 5); This means that John is 35, Mary is 30 and so on.
When the information from a hash is needed it is called through a scalar variable + the key, for example: "$Family_age{John}" will equal the value of 35.

1.5.4 Use the print command.

The print command is responsible for output in Perl. To utilize it you must type "print" and then the desired output.

For example: "print $name" will output "John Anderson" because you assigned that value to "$name" in Step 1. Likewise, Print @Anderson_family will output all of the names that were assigned to this array.


1.5.5 Create a program.

This program will output some of the variables you created. To do this type the following;

#!/usr/bin/perl
$name = "John Anderson";
$age = 35;
@Anderson_family = ("John","Mary", "Julie", "Mark");
%Family_age = ("John" => 35, "Mary" => 30, "Julie" => 7, "Mark" => 5);
print "$name is $age years old\n";
print "@Anderson_family\n";
print "Mary is $Family_age{Mary} years old and Mark is $Family_age{Mark} years old";

The '\n' character makes sure that a new line follows what is printed out. Save the program as "family.pl" in a known directory.

Here are some methods can be used in Perl Script,

Construction and Generic Method:

• Win32::IEAutomation->new( visible => 1, maximize => 1, warnings => 1 )

This is the constructor for new Internet Explorer instance through Win32::OLE. Calling this function will create a perl object which internally contains a automation object for internet explorer. Three options are supported to this method in hash format. All of these are optional.

• Visible

It sets the visibility of Internet Explorer window. The default value is 1, means by default it will be visible if you don't provide this option. You can set it to 0 to run it in invisible mode.

• maximize

Default value of this is 0, means it runs IE in the size of last run. Setting this to 1 will maximize the window.

• warnings

Default value of this is 0. If you want to print warning messages for any object not found, then set it to 1. This is optional.

• gotoURL($url, [$nowait])

This method navigates to the given url and waits for it to be loaded completely if second argument is not provided Second argument is optional and it represents the boolean value for not waiting till page gets loaded. Giving second argument as 1 (true boolean value) makes your code not to wait for page loading in this 'gotoURL' method. This is useful if you need to interact with any dialog like security alert. In that case use this method with second argument, then interact with dialog (methods for interacting with dialog are described below) and then using method 'WaitforDone' (described below) wait for IE to load page completely.

• Back()

Works as IE's Back button and waits for it to be loaded completely

• Reload()

Works as IE's Refresh button and waits for it to be loaded completely

• URL()

This will return the URL of the current document

• Title()

This will return title of the current document

• Content()

This will return the HTML of the current document. In scalar context return a single string (with \n characters) and in list context returns array. Please note that all the tags are UPPER CASED.

• VerifyText($string, [iflags])

Verifies that given string is present in the current document text. It returns 1 on success and undefined on failure. Second parameter iflags is optional. It is integer value that specifies one or more of the following flags to indicate the type of search.
0 - Default. Match partial words.
1 - Match backwards.
2 - Match whole words only.
4 - Match case.
• PageText()

It returns the text in the current page. (no html tags). In scalar context return a single sting (with \n characters) and in list context returns array.

It will assist for using VerifyText method. User can print the returned array to some file and see what string he/she can pass as an argument to the VerifyText method.

• WaitforDone()

Waits till IE had came out of busy state and document is loaded completly. This will poll IE for every one second and check its busy state and document complete state, before we move on.

• closeIE()

It will close the instance of internet explorer.

• getAgent()

It will return a reference to the Internet Explorer automation object, created using Win32::OLE.

• getProperty($property)

Retrieves the value of the given property for any of the below given objects. This makes easy to get value of any property that is supported by html link.


Link Methods:

• getLink($how, $what)

This is the method to access link on web page. It returns Win32::IEAutomation::Element object containing html link element.

$how : This is the option how you want to access the link

$what : This is string or integer, what you are looking for. For this, it also supports pattern matching using 'qr' operator of perl (see example below)


Valid options to use for $how:


o 'linktext:' - Find the link by matching the link text i.e. the text that is displayed to the user

o 'id:' - Find the link by matching id attribute

o 'name:' - Find the link by matching name attribute

o 'linkurl:' - Find the link by matching url attribute of the link

o 'class:' - Find the link by matching class attribute

$ie->getLink('linktext:', "Sign in"); # access the link that has Sign in as its text
$ie->getLink('linktext:', qr/About Google/); # access the link whose text matches with 'About Google'
$ie->getLink('id:', 5); # access the link whose id attribute is having value 5

• getAllLinks()

This will return a list of all links present in the current document, in form of Win32::IEAutomation::Element objects. For return value, in scalar context, gives number of links present and in list context gives array of all link objects. Each object in the array is similar to one we get using getLink method.

Image Methods:

• getImage($how, $what)

This is the method to access image on web page. It returns Win32::IEAutomation::Element object containing html image element.

$how : This is the option how you want to access the image

$what : This is string or integer, what you are looking for. For this, it also supports pattern matching using 'qr' operator of perl (see example below)

Valid options to use for $how:

o 'id:' - Find the image by matching id attribute

o 'name:' - Find the image by matching name attribute

o 'imgurl:' - Find the image by matching src attribute of the image

o 'alt:' - Find the image by matching alt attribute of the image

o 'class:' - Find the image by matching class attribute

$ie->getImage('imgurl:', qr/logo.gif$/); # access the image that matches logo.gif at last of string of its url (src)
$ie->getImage('alt:', "Google"); # access the image whose alt attribute is 'Google'
$ie->getImage('class:', $some_class); # access the image whose class attribute is having value $some_class

• getAllImages()

This will return a list of all images present in the current document, in form of Win32::IEAutomation::Element objects. For return value, in scalar context, gives number of images present and in list context gives array of all image objects. Each object in the array is similar to one we get using getImage method.

Button Methods:

• getButton($how, $what)

This is the method to access button on web page. It returns Win32::IEAutomation::Element object containing html input type=button or submit element.

$how : This is the option how you want to access the button

$what : This is string or integer, what you are looking for. For this, it also supports pattern matching using 'qr' operator of perl (see example below)

Valid options to use for $how:

o 'id:' - Find the button by matching id attribute

o 'name:' - Find the button by matching name attribute

o 'value:' - Find the button by matching value attribute

o 'caption:' - Find the button by matching text shown on button

o 'class:' - Find the button by matching class attribute

If there are more than one button having same value for the option you are quering, then it returns first button of the collection.

$ie->getButton('caption:', "Google Search"); # access the button with 'Google Search' as its caption
$ie->getButton('name:', "btnG"); # access the button whose name attribute is 'btnG'

Radio and Checkbox Methods:


• getRadio($how, $what)

This is the method to access radio button on web page. It returns Win32::IEAutomation::Element object containing html input type=radio element.

• getCheckbox($how, $what)

This is the method to access checkbox on web page. It returns Win32::IEAutomation::Element object containing html input type=checkbox element.

$how : This is the option how you want to access the radio or checkbox

$what : This is string or integer, what you are looking for. For this, it also supports pattern matching using 'qr' operator of perl (see example below)

Valid options to use for $how:

o 'id:' - Find the radio or checkbox by matching id attribute

o 'name:' - Find the radio or checkbox by matching name attribute

o 'value:' - Find the radio or checkbox by matching value attribute

o 'class:' - Find the radio or checkbox by matching class attribute

o 'index:' - Find the radio or checkbox using the index in the total collection of the radio or checkbox. (see example below)

o 'beforetext:' - Find the radio or checkbox before the specified text.

o 'aftertext:' - Find the radio or checkbox after the specified text.

If there are more than one object having same value for the option you are quering, then it returns first object of the collection.

$ie->getRadio('beforetext:', "Option One"); # access the radio which appears before text 'Option One'
$ie->getRadio('value:', $radio_value); # access the radio whose value attribute is $radio_value
$ie->getCheckbox('aftertext:', "Remember Password"); # access the checkbox which appears after text 'Remember Password'
$ie->getCheckbox('index:', 3); # access third checkbox from the collection of checkbox on the current web page.

Methods supported for radio or checkbox object

• Select()

It selects the specified radio or checkbox, provided it is not already selected.

$ie->getRadio('beforetext:', "Option One")->Select;

• deSelect()
It deselects the specified radio or checkbox, provided it is not already deselected.

$ie->getCheckbox('aftertext:', "Remember Password")->deSelect;

Select List Methods:


• getSelectList($how, $what)

This is the method to access select list on web page. It returns Win32::IEAutomation::Element object containing html select element.

$how : This is the option how you want to access the select list

$what : This is string or integer, what you are looking for. For this, it also supports pattern matching using 'qr' operator of perl (see example below)

Valid options to use for $how:

o 'id:' - Find the select list by matching id attribute

o 'name:' - Find the select list by matching name attribute

o 'class:' - Find the select list by matching class attribute

o 'index:' - Find the select list using the index in the total collection of the select lists. (see example below)

o 'beforetext:' - Find the select list before the specified text.

o 'aftertext:' - Find the select list after the specified text.

If there are more than one object having same value for the option you are quering, then it returns first object of the collection.

$ie->getSelectList('aftertext:', "some text"); # access the select list which appears after text 'some text'
$ie->getSelectList('name:', 'time_zone'); # access the select list whose name attribute is 'time_zone'
$ie->getSelectList('index:', 3); # access third select list from the collection of select lists on the current web page.

Methods supported for select list object

• SelectItem()

It selects one or more items from the select list. You can pass a single or multiple item to this method. Provide the name of item which is visible to user on web page ( and not that is in html code). Use this method for selection of multiple items only if select list is supporting multiple selection.

$ie->getSelectList('name:', 'time_zone')->SelectItem("India"); # selects one item "India" in the select list
$ie->getSelectList('name:', 'time_zone')->SelectItem("India", "U. S. A.", "Australia"); # selects three items "India", "U. S. A." and "Australia" in the select list

• deSelectItem()

It deselects one or more items from the select list. You can pass a single or multiple item to this method. Provide the name of item which is visible to user on web page ( and not that is in html code)

$ie->getSelectList('name:', 'time_zone')->deSelectItem("India"); # deselect one item "India" in the select list
$ie->getSelectList('name:', 'time_zone')->deSelectItem("India", "U. S. A.", "Australia"); # deselect three items "India", "U. S. A." and "Australia" in the select list

• deSelectAll()

It deselects all items from the select list. Call this method without any argument. This method is useful, when a select list appears with a random selected item and you need to deselect that.

$ie->getSelectList('name:', 'time_zone')->deSelectAll(); # deselect all items in the select list

Textbox and Textarea Methods:

• getTextBox($how, $what)

This is the method to access input text field on web page. It returns Win32::IEAutomation::Element object containing html input type=text or password element. Additionaly this method works for file upload text field also. (i.e. input type=file).

• getTextArea($how, $what)

This is the method to access input text area on web page. It returns Win32::IEAutomation::Element object containing html textarea element.

$how : This is the option how you want to access the select list

$what : This is string or integer, what you are looking for. For this, it also supports pattern matching using 'qr' operator of perl (see example below)

Valid options to use for $how:

o 'id:' - Find the text field by matching id attribute

o 'name:' - Find the text field by matching name attribute

o 'value:' - Find the text field by matching value attribute

o 'class:' - Find the text field by matching class attribute

o 'index:' - Find the text field using the index in the total collection of the text fields. (see example below)

o 'beforetext:' - Find the text field before the specified text.

o 'aftertext:' - Find the text field after the specified text.

If there are more than one object having same value for the option you are quering, then it returns first object of the collection.

Methods supported for text field object

• SetValue($string)

It will set the value of text field or text area to the string provided.

$ie->getTextBox('name:', "q")->SetValue("web automation"); # it will enter text 'web automation' in the input text filed.
$ie->getTextBox("name:", "importFile")->SetValue("C:\\temp\\somefile"); # to set somefile in file upload text field

• GetValue()

It will return the default text present in the textbox or text area.

$ie->getTextBox('name:', "q")->GetValue() # return the default text present in the textbox

• ClearValue()

It will clear the text field.

$ie->getTextBox('name:', "q")->ClearValue() # it will clear the input text field.


Table Methods:

• getTable($how, $what)

This is the method to access table on web page. It returns Win32::IEAutomation::Table object containing html table.

$how : This is the option how you want to access the link

$what : This is string or integer, what you are looking for. For this, it also supports pattern matching using 'qr' operator of perl (see example below)

o Valid options to use for $how:
o 'id:' - Find the table by matching id attribute

o 'name:' - Find the table by matching name attribute

o 'value:' - Find the table by matching value attribute

o 'class:' - Find the table by matching class attribute

If there are more than one object having same value for the option you are quering, then it returns first object of the collection.

$ie->getTable("id:", "1a"); # access the table whose id attribute is '1a'
$ie->getTable("class:", "data") # access the table whose class attribute is 'data'

• getAllTables()

This will return array containing all table on that page. Each element of an array will be a Win32::IEAutomation::Table object.

my @alltables = $ie->getAllTables;

Methods supported for table object

• rows([index of row])

This method returns the row object/objects from the table. It takes an optional argument, the index number of the row you wish to take. If this method is used without any argument then it returns array of row objects in the table. And if you provide an argument, then it returns a scalar row object present at specified index. The rows are counted inclusing header row.

my @all_rows = $table_object->rows; # get collection of all row objects in the table
my $third_row = $table_objects->rows(3) # get third row of the table.



• getRowHavingText($string);

This method returns a single row object that contains specifed text. If the text string is present in any of the row of the table, then that row objetc is returned. This method supports perl pattern matching using 'qr' operator.

my $target_row = $table_object->getRowHavingText("Last Name:"); # access the row which contains text "Last Name:". It will try to match eaxact string.
my $target_row = $table_object->getRowHavingText(qr/First Name:/); # access the row by pattern matching text "First Name:"

• tableCells([$row, $column])

This method returns an array of all cell objects present in the table. Each element of the array will be a cell object. Please see below for methods on cell object. Additionaly it also supports two optional parameters, first parameter is index of the row and second is index of column. When these two parameters are used, it returns a scalar cell object using combination of row and column index.

my @allcells = $table_object->tableCells; # get all cell objects in an array
my $target_cell = $table_object->tableCells(2, 5); # get cell at second row and fifth column

Methods supported for row object

• cells([index of cell])

This methos returns an array of cell objects present in that cell. Each elemnt of an array will be a cell object. Additionaly it supports one optional parameter, cell index. If this method is used without any argument then it returns array of cell objects in that row. And if you provide an argument, then it returns a scalar cell object present at specified index.

my @all_cells = $row_object->cells; # get collection of all cell objects in that row
my $third_cell = $table_objects->cells(3) # get third cell of that row.

Methods supported for cell object

• cellText

It returns a text present in that cell.

$text = $cell_object->cellText; # access the text present in that cell.
Frame Method

• getFrame($how, $what)

It will return the Win32::IEAutomation object for frame document. Frame document is having same structure as that of parent IE instance, so all methods for link, button, image, text field etc. are supported on frame object.

$how : This is the option how you want to access the select list

$what : This is string or integer, what you are looking for. For this, it also supports pattern matching using 'qr' operator of perl (see example below)

Valid options to use for $how:

o 'id:' - Find the frame by matching id attribute

o 'name:' - Find the frame by matching name attribute

o 'value:' - Find the frame by matching value attribute

o 'class:' - Find the frame by matching class attribute

$ie->getFrame('id:', "f1"); # access the frame whose id attribute is 'f1'
$ie->getFrame('name:', 'groups'); # access the frame whose name attribute is 'groups'

To control any objects under frame, first get the frame object using 'getFrame' method and then use other methods (getLink, getRadio etc.) to access objects.

$ie->getFrame('name:', 'groups')->getRadio('beforetext:', "Option One")->Select; # select the radio which is under frame.

There might be case of frame inside frame (nested farmes), so use getFrame method uptp target frame

$ie->getFrame("name:", "first_frame")->getFrame("name:", "nested_frame");

Popup Methods:

• getPopupWindow($title)

It will return the Win32::IEAutomation object for popup window. Popup window is having same structure as that of parent IE instance, so all methods for link, button, image, text field etc. are supported on popup object.

Provide the exact title of the popup window as an argument to this method.

$ie->getPopupWindow("Popup One"); # access the popup window whose title is "Popup One"

To control any objects under popup, first get the popup object using 'getPopupWindow' method and then use other methods (getLink, getRadio etc.) to access objects.

my $popup = $ie->getPopupWindow("Popup One") # access the popup window
$popup->getRadio('beforetext:', "Option One")->Select; # select the radio

There might be case where popup takes time to load its document, so you can use 'WaitforDone' method on popup

my $popup = $ie->getPopupWindow("Popup One") # access the popup window
$popup->WaitforDone; # wait so that popup will load its document completely

Dialog Handling Methods:

Win32::IEAutomation::WinClicker class provides some methods to ineract with dialogs like security alert, confirmation dialog, logon dialog etc. COM interface to AutoIt (http://www.autoitscript.com/autoit3/) is used to implement these.

You need to create a new instance of Win32::IEAutomation::WinClicker and then use these methods.

• Win32::IEAutomation::WinClicker->new( warnings => 1)

warnings

Default value of this is 0. If you want to print warning messages for any object not found, then set it to 1. This is optional.

• push_security_alert_yes($wait_time)

It will push the 'Yes' button of Security Alert dialog box. Provide wait time so that it will wait for Security Alert dialog box to appear. Default value of wait time is 5 seconds (if wait time is not provided). It will timeout after wait time, and execute next line of code.

• push_button_yes($title, $wait_time)

It will push 'Yes' button of window which is having provided title.

$title: Provide exact title of dialog box

$wait_time: Provide wait time so that it will wait for confirmation dialog box to appear. Default value of wait time is 5 seconds (if wait time is not provided). It will timeout after wait time, and execute next line of code.

• push_confirm_button_ok($title, $wait_time)

It will push the 'OK' button of any confirmation dialog box.

$title: Provide exact title of dialog box

$wait_time: Provide wait time so that it will wait for confirmation dialog box to appear. Default value of wait time is 5 seconds (if wait time is not provided). It will timeout after wait time, and execute next line of code.

• push_confirm_button_cancle($wait_time)

It will push the 'Cancle' button of any confirmation dialog box.

$title: Provide exact title of dialog box

$wait_time:
Provide wait time so that it will wait for confirmation dialog box to appear. Default value of wait time is 5 seconds (if wait time is not provided). It will timeout after wait time, and execute next line of code.

• logon($title, $user, $password, $wait_time)

It will fill the logon dialog box with user name and password, and then press enter.

$title: Provide exact title of logon doalog box

$user: Provide user name to enter

$password: Provide password to enter

$wait_time: Provide wait time so that it will wait for logon dialog box to appear. Default value of wait time is 5 seconds (if wait time is not provided). It will timeout after wait time, and execute next line of code.


1.6 How to run a Perl script?

Now to run perl script from your desktop, you have to travel through the command prompt to your desktop directory.

Then call the PERL command followed by your file name. If our file was “test.pl” , we'd type in
perl test.pl.


Sample Code
# script for listing out AR numbers...

#modules to be included.

# jump1 - exit 1 loops

use strict;

use Win32::OLE qw(in with);

use Win32::OLE::Const 'Microsoft Excel';

use Win32::IEAutomation;

#My declarations

my $count=0;
my $file;
my $cel1;
my $row;
my $occ=0;
my $flag=0;
my $count=0;
$Win32::OLE::Warn = 3;
my $text;



#Creation of Excel object
my $Excel = Win32::OLE->GetActiveObject('Excel.Application') || Win32::OLE->new('Excel.Application', 'Quit');
my $Book = $Excel->Workbooks->Open("D:/PerlProject/wmp1.xls");
my $Sheet = $Book->Worksheets(1);
#getting the used range of excel sheet from auto.xcl
my $Tot_Rows= $Sheet->UsedRange->Rows->{'Count'};
#print $Tot_Rows;

#opening IE instance
my $ie = Win32::IEAutomation->new(maximize => 1);

#goto idm admin page
$ie->gotoURL("https://idmt.mypepsico.com/idm/user/processLaunch.jsp?newView=true&id=CobraManagerProfileManagement", 1);
my $clicker = Win32::IEAutomation::WinClicker->new();
$clicker->logon("Connect to snowy1.wipro.com", "username", "password","5");
#wait for page load
$ie->WaitforDone;

#https://idmt.mypepsico.com/idm/user/processLaunch.jsp?newView=true&id=CobraManagerProfileManagement
#supplying user name and password to the web page
$ie->getTextBox('name:', "ldap_uid")->SetValue("username");
$ie->getTextBox('name:', "ldap_password")->SetValue("password");
$ie->getButton('value:', "Log In")->Click;
$ie->WaitforDone;

#logic for listing out AR numbers
foreach my $row (1..$Tot_Rows)
{

my $cel=$Sheet->Cells($row,6)->{'Value'};
$ie->getSelectList('name:', 'variables.search.type')->SelectItem("Email");
$ie->getTextBox('name:',"variables.search.criteria")->SetValue($cel);
$ie->getButton('value:', "Search")->Click;
$ie->WaitforDone;
my $radiotext = $ie->getRadio('name:', "variables.userSearch");
if(defined $radiotext){
$text = "'".$radiotext->getProperty("value");
}else{
$text = "UNDEF";
}
$ie->WaitforDone;
$Sheet->Cells($row,7)->{'Value'}= $text;
}
$Book->Save;
$Book->Close;



Reference :

http://www.webopedia.com/TERM/P/Perl.html

http://www.cs.cf.ac.uk/Dave/PERL/node3.html

http://perldoc.perl.org/perlintro.html

http://search.cpan.org/~prashant/Win32-IEAutomation-0.5/slib/Win32/IEAutomation.pm

http://www.gossland.com/course/intro/examples.html

http://www.ehow.com/how_5092633_write-perl-script.html

http://alumnus.caltech.edu/~svhwan/prodScript/invokingPerl.html

http://www.hiteksoftware.com/knowledge/articles/035.htm