Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
iMacros Command, Variable, and function reference

iMacro CheatSheet - Command Reference

Variables

iMacros supports 3 types of variables

  • The macro variables !VAR0 thru !VAR9. They can be used with the SET and ADD command inside a macro.
  • Built-in variables. They contain certain values set by iMacros.
  • User-defined variables. They are defined in-macro using the SET command.

Commands Reference.

' comment The single quote character ' indicates a comment. If a line starts with ' everything else on this line is ignored. Typically this is used for comments or to disable specific parts of a macro.

ADD !VAR value Add a value to a variable. You can also substract values by adding a negative value to the variable.

BACK Opens the previously visited website.

CLEAR Clears the browsers cache and all cookies.

CLICK X=n Y=m Clicks on the HTML element at the specified X/Y coordinates.

SET !VAR1 EVAL('[javascript statements]') This command allows you to evaluate values, and trigger macro errors if certain conditions are met.

FILEDELETE NAME=file_name Deletes the file specified by Name. If no directory is specified in Name the file is assumed to lie in the iMacros Downloads subdirectory.

FILTER TYPE=IMAGES STATUS=(ON|OFF) Filtering is a feature that allows you to change data on the website before it reaches the browser. Currently only the TYPE=IMAGES filter is supported.

FRAME (F=n|NAME=id) Directs all following TAG or EXTRACT commands to the specified frame. The frame tag and number is automatically generated by clicking into a framed web page.

ONCERTIFICATEDIALOG C=n BUTTON=[OK|CANCEL] Selects the client side certificate at position C from the upcoming dialog.

ONDIALOG POS=n BUTTON=(YES|NO|CANCEL) [CONTENT=some_content] Handles upcoming Javascript dialogs. You can extract the text of a dialog by adding SET !EXTRACTDIALOG YES to your macro.

ONDOWNLOAD FOLDER=folder_name FILE=file_name WAIT=[YES|NO] CHECKSUM=[MD5|SHA:hexadecimal_string] iMacros automatically detects and intercepts downloads. With this command, which has to occur before the download starts, the location and name of the saved file is determined.

ONERRORDIALOG BUTTON=(YES|NO) CONTINUE=(YES|NO) If a page script error occurs on a webpage Internet Explorer opens an error dialog. This command handles such a dialog so your macros are not interrupted by script errors.

ONLOGIN USER=username PASSWORD=password RETRY=[YES|NO] Handles login dialogs. The ONLOGIN command must appear before the macro command that navigates to the site that brings up the login dialog.

ONPRINT P=n BUTTON=(PRINT|CANCEL) Handles print dialogs. The ONPRINT command must appear before the PRINT command which triggers the printer dialog to come up.

ONSECURITYDIALOG BUTTON=(YES|NO) CONTINUE=(YES|NO) Command to handle security dialogs. If Continue=No is selected then the macro will stop if such a dialog appears.

ONWEBPAGEDIALOG KEYS=some_keys|MACRO=macro_file Web page dialogs are similar to Javascript dialogs except they display HTML content.

PAUSE Same as a manual click of the Pause button: Stops the execution of the macro. Waits for user to click Continue to continue.

PRINT Prints the current browser window on your default printer.

PROMPT prompt_text variable_name [default_value] Displays a popup to ask for a value. This value is stored in variable_name. This command can be used to change the variables !VAR1, !VAR2 or !VAR3, but not built-in variables like !DATASOURCE or dynamically generated variables.

PROXY ADDRESS=proxy_URL:port [BYPASS=page_name] Connect to a proxy server to run the current macro.

REFRESH Refreshes (Reloads) current browser window. Refresh includes sending a pragma:nocache header to the server (HTTP URLs only) which causes all elements of the website to be reloaded from the webserver.

SAVEITEM SAVEITEM saves the document that is currently displayed in the web browser, for example a PDF file.

SAVEAS TYPE=(CPL|MHT|HTM|TXT|EXTRACT|BMP|PNG|JPEG) FOLDER=folder_name FILE=file_name Saves information to a file. The SAVEAS command can save different information to a file.

SCREENSHOT TYPE=(PAGE|BROWSER) FOLDER=folder_name FILE=file_name With this command, iMacros can take a screenshot of the Page/Browser that is being displayed.

SEARCH SOURCE=(TXT|REGEXP) IGNORE_CASE=YES EXTRACT=$1 The SEARCH commands works with page source, instead of looking at the web page object model (DOM) that the TAG command uses.

SET var value Defines the value of a variable. The SET command supports the built-in variables, pre-defined user variables !VAR0 thru !VAR9, as well as user-defined macro variables.

SIZE X=n Y=m Resizes the browser window.

TAB (T=n|OPEN|CLOSE|CLOSEALLOTHERS) Sets focus on the tab with number n.

STOPWATCH ID=id Measures the time in seconds between two STOPWATCH commands with the same identifier.

TAG POS=1 TYPE=SELECT FORM=NAME:form1 ATTR=NAME:select1 CONTENT=$Apple The TAG command selects HTML elements from the current website. The identification of the element is given by providing the parameters POS, TYPE, FORM and ATTR. If the selected element is a link then the link is followed, i.e. the TAG command acts as if it clicks on the element.

TRAY (HIDE|SHOW) Hides or shows the iMacros Browser during playback. A tray icon appears instead of the browser, just like with the command line switch -tray.

URL GOTO=some_URL Navigates to a URL in the currently active tab.

VERSION BUILD=<version number> Specifies the version of iMacros that created this macro. Please note this command is required by all macros.

WAIT SECONDS=(n|#DOWNLOADCOMPLETE#) Waits for a specific time before continuing replay with the next command (timed delay).

Built-In Variables.

!CLIPBOARD Copy data from and to the clipboard.

!COLn Specifies the column which is used for input. Set n to the column number you want to use.

!DATASOURCE Specifies the name and location of an input file for merging data with macro.

!DATASOURCE_COLUMNS Specifies the number of columns in the input datasource.

!DATASOURCE_DELIMITER Specifies the character used to delimit fields in your CSV input file.

!DATASOURCE_LINE Specifies the line in the datasource which is used for input.

!ENCRYPTION Specifies how to encrypt passwords you use in macros.

!ENDOFPAGE Uses the !TAGSOURCEINDEX variable to define the end of page for iMacros. A search for a TAG element does not go below this limit.

!ERRORIGNORE Tells iMacros to ignore errors. The replay of macros continues even if one or more commands fail.

!EXTRACT Contains the extraction results.

!EXTRACT_TEST_POPUP Toggles whether the extraction result in displayed during replay in a popup dialog.

!EXTRACTDIALOG Extract information from a dialog. The entire text of a website dialog is extracted.

!FILE_LOG Sets a specific log file name for the current macro. If no folder is supplied then the file will be written to the standard log file directory (V7.x) or the download directory (up to V6) of your iMacros installation.

!FILE_STOPWATCH Sets the file name for the file that contains the stopwatch measurement data. By default the file name is performance_macroname.csv and is located in the download directory of your iMacros installation.

!FILE_PROFILER Sets the file name for the file that contains the performance profile data and enables profiling. By default all performance output of a given day is stored in the file Profiler_yyyy-MM-dd.xml, located in the download directory of your iMacros installation.

!FOLDER_DATASOURCE Returns/sets the folder from which input files are read in by default. Setting this variable is valuable if several macros share an input file folder, or to separate the image files that each macro needs.

!FOLDER_STOPWATCH Sets the folder location for the file that contains the stopwatch measurement data.

!IMAGEX This value contains the X-coordinate of the last image found with the IMAGESEARCH or IMAGECLICK command. If the last image search did not find an image, then the value is -1.

!IMAGEY This value contains the Y-coordinate of the last image found with the IMAGESEARCH or IMAGECLICK command.

!LOOP Counts the current loop number in loop mode. Especially useful together with the POS attribute of the TAG command. With SET !LOOP 3 you can set a start value for the loop counter (the default value is 1).

!MARKOBJECT Toggles whether a border should be drawn around the tagged element. The default value is YES.

!NOW Contains the current time and date. In order to format the time and date you can use the following format codes, which you need to append to the variable after a colon.

!POPUP_ALLOWED Allow popups for a given URL during a macro run. Technically this is the same as white-listing the URL permanently. The advantages are that you can store this information in the macro and thus make it run everywhere, without the user having to manually white-list the URL.

!REPLAYSPEED Sets the replay speed to fast, medium or slow.

!REGION_BOTTOM Defines the bottom boundary of a subregion to restrict IMAGESEARCH. For very large pages this should reduce the time needed for IMAGESEARCH.

!REGION_LEFT Defines the left boundary of a subregion to restrict IMAGESEARCH. For very large pages this should reduce the time needed for IMAGESEARCH.

!REGION_RIGHT Defines the right boundary of a subregion to restrict IMAGESEARCH. For very large pages this should reduce the time needed for IMAGESEARCH.

!REGION_TOP Defines the top boundary of a subregion to restrict IMAGESEARCH. For very large pages this should reduce the time needed for IMAGESEARCH.

!SINGLESTEP Enables single-step debugging: iMacros stops after every command and waits for the user to click the Continue button.

!STOPWATCHTIME Contains the last measured response time value.

!STOPWATCH_HEADER If set to NO tells iMacros to omit the header in the output performance file.

!TAGSOURCEINDEX Retrieves the ordinal position of the object, in source order, as the object appears in the document's all collection.

!TAGX This value contains the X-coordinate of the HTML element found with the TAG command. The !TAGX/!TAGY values are automatically set after each TAG command.

!TAGY This value contains the Y-coordinate of the HTML element found with the last TAG command.

!TIMEOUT_MACRO Set the macro's global timeout in seconds.

!TIMEOUT_PAGE Set the page load timeout in seconds.

!TIMEOUT_STEP Sometimes text or images do not appear immediatly after a page is loaded.

!URLCURRENT Contains the current URL. This is the URL visible in the browser address bar at the time the variable is used.

!USERAGENT Change the default user agent of the web browser.

!VAR0...!VAR9 Standard built-in variables for arbitrary use.

!WAITPAGECOMPLETE If this variable is set to YES iMacros will wait until the top frame is completely loaded.

Scripting Interface Commands.

ret_code = iimOpen(String commandLine [, boolean openNewBrowser] [, int timeout]); Initializes the Scripting Interface. It opens a new instance of the iMacros Browser, IE or Firefox, or connects to an existing instance (depending on the specified parameters). If the command fails for any reason it returns an error code.

ret_code = iimDisplay(String message [, int timeout]); Displays a short message in the iMacros browser. A typical usage would be to distinguish several running iMacros Browsers or display information on the current position within the script.

ret_code = iimPlay(String macro [, int timeout]); Plays a macro. After the macro has played all options that have been set with the iimSet command are reset. Use iimGetLastExtract to get the extracted text.

ret_code = iimSet(String VARNAME, String VARVALUE); Defines variables for use inside the macro and assigns values to them.

ret_code = iimTakeBrowserScreenshot(String FILEPATH, int 0/1); Takes a screenshot of the current browser content or the current website.

ret_code = iimClose([int timeout]); Closes the iMacros browser.

ret = iimGetStopwatch(int index, string name, string value); Returns the data of the STOPWATCH command. If there is no STOPWATCH command in the macro then iimGetStopwatch returns only one value (Total Runtime).

err_message = iimGetErrorText(); Returns the text associated with the last error.

extract = iimGetExtract([int index_of_extracted_text]); Returns the contents of the !EXTRACT variable.

macro_node = iimGetPerfomance(); Returns the XML fragment containing the performance data of the last macro run, if performance logging has been enabled.

version_number = iimGetInterfaceVersion(); It returns a number in LONG format such as 80066532. Note that the iMacros main version number (as shown by VERSION) and the Scripting Interface version number as shown by iimGetInterfaceVersion are not identical.

Functions

Simulate a keypress

URL GOTO=javascript:var<SP>evt=document.createEvent("KeyboardEvent");evt.initKeyEvent("keyup",true,true,window,0,0,0,0,13,13);document.getElementById("TEXTBOX").dispatchEvent(evt);document.focus();

Output a file in UTF-8

function writeToFile(filename, data) {
    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } catch (e) {
        alert("Permission to save file was denied.");
        return 0;
    }
    var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);

    var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);

    var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"].createInstance(Components.interfaces.nsIConverterOutputStream);

    file.initWithPath( filename );
    outputStream.init( file, 0x02|0x08|0x20, 0644, 0 );

    // write BOM first, then converted data.
    outputStream.write('\u00EF\u00BB\u00BF', 3);

    converter.init(outputStream, "UTF-8", 0, 0);
    converter.writeString(data);
    converter.close(); // this closes outputStream also
}

Working with Image Maps

VERSION BUILD=6000707
TAB T=1
TAB CLOSEALLOTHERS
SET !REPLAYSPEED SLOW
URL GOTO=http://www.mls.ca/
SIZE X=876 Y=627
TAG POS=1 TYPE=AREA ATTR=HREF:http://www.mls.ca/map.aspx?AreaID=6240
TAG POS=1 TYPE=AREA ATTR=HREF:http://www.mls.ca/map.aspx?AreaID=8689
TAG POS=1 TYPE=AREA ATTR=HREF:http://www.mls.ca/map.aspx?AreaID=6287
TAG POS=1 TYPE=AREA ATTR=HREF:http://www.mls.ca/map.aspx?AreaID=6464
TAG POS=1 TYPE=AREA ATTR=HREF:http://www.mls.ca/PropertySearch.aspx?AreaID=5634&MapURL=%3fAreaID%3d6464
'Comment: New page loaded

Determine iMacros folder location from Javascript

function getiMacrosFolder(folderName) {
   var pname;
   switch (folderName) {
      case "Macros" :
         pname = "defsavepath";
         break;
      case "DataSources" :
         pname = "defdatapath";
         break;
      case "Downloads" :
         pname = "defdownpath";
         break;
      case "Logs" :
         pname = "deflogpath";
         break;
      default :
         throw folderName + " is not a valid iMacros folder name";
         break;
   }
   return imns.Pref.getFilePref(pname).path;
}

var downloadFolder = getiMacrosFolder("Downloads");

Automate Creation of Google Accounts (disable JS in browser before running)

VERSION BUILD=5200814
TAB T=0
TAB CLOSEALLOTHERS
CLEAR
SET !ENCRYPTION NO
URL GOTO=https://www.google.com/accounts/Login
PROMPT username !VAR1
TAG POS=1 TYPE=INPUT:PASSWORD FORM=ACTION:LoginAuth ATTR=ID:Passwd CONTENT=
TAG POS=1 TYPE=B ATTR=TXT:Create<SP>an<SP>account<SP>now<SP>
SET !VAR2 {{!VAR1}}
ADD !VAR2 @temporaryinbox.com
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:createaccount ATTR=NAME:Email CONTENT={{!VAR2}}
TAG POS=1 TYPE=INPUT:PASSWORD FORM=NAME:createaccount ATTR=NAME:Passwd CONTENT=YOURPASSWORD
TAG POS=1 TYPE=INPUT:PASSWORD FORM=NAME:createaccount ATTR=NAME:PasswdAgain CONTENT=YOURPASSWORD
TAG POS=1 TYPE=SELECT FORM=NAME:createaccount ATTR=ID:loc CONTENT=228
PROMPT captcha !VAR3
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:createaccount ATTR=ID:newaccountcaptcha CONTENT={{!VAR3}}
TAG POS=1 TYPE=INPUT:SUBMIT FORM=NAME:createaccount ATTR=ID:submitbutton&&VALUE:I<SP>accept.<SP>Create<SP>my<SP>account.
'
'Verify Email
'
'Wait a few seconds for email to arrive
WAIT SECONDS=3
'
'
URL GOTO=http://www.temporaryinbox.com/
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:quickaccess ATTR=NAME:inbox CONTENT={{!VAR1}}
TAG POS=1 TYPE=INPUT:IMAGE FORM=NAME:quickaccess ATTR=NAME:&&VALUE:
TAG POS=1 TYPE=TD ATTR=TXT:accounts-noreply@google*
TAG POS=1 TYPE=B ATTR=TXT:http://www.google.com/accounts/VE?c=*
TAB T=2
'Done!

Delete User Facebook Activity

VERSION BUILD=8920312
TAB T=1
SET !ERRORIGNORE YES
URL GOTO=https://www.facebook.com/<YOUR FACEBOOK USERNAME HERE>/allactivity?privacy_source=activity_log&log_filter=cluster_11
' Eventually, depending on how many posts there are, you'll need to start manually skipping to years.
' Uncomment the line below and decrement the year as needed.
'TAG POS=1 TYPE=A ATTR=HREF:/< USERNAME >/timeline/2010
WAIT SECONDS=5
URL GOTO=javascript:window.scrollBy(0,100000)
TAG POS=1 TYPE=A ATTR=aria-label:"Allowed on Timeline"
TAG POS=2 TYPE=SPAN ATTR=TXT:Delete
WAIT SECONDS=1
TAG POS=1 TYPE=BUTTON FORM=class:_s ATTR=TXT:Delete<SP>Post
WAIT SECONDS=252525

Captcha Solver

VERSION BUILD=8820413 RECORDER=FX
TAB T=1

ONDOWNLOAD FOLDER=c:\ FILE=captcha.jpg

TAG POS=1 TYPE=IMG ATTR=HREF:*captcha* CONTENT=EVENT:SAVE_ELEMENT_SCREENSHOT

SET !EXTRACT_TEST_POPUP NO
TAB OPEN
TAB T=2

URL GOTO=http://api.captchasolutions.com/solve
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://api.captchasolutions.com/solve ATTR=NAME:p CONTENT=imacros
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://api.captchasolutions.com/solve ATTR=NAME:key CONTENT=YOUR_API_KEY_HERE
TAG POS=1 TYPE=INPUT:TEXT FORM=ACTION:http://api.captchasolutions.com/solve ATTR=NAME:secret CONTENT=YOUR_SECRET_KEY_HERE
TAG POS=1 TYPE=INPUT:FILE FORM=ACTION:http://api.captchasolutions.com/solve ATTR=NAME:captcha CONTENT=C:\captcha.jpg
TAG POS=1 TYPE=INPUT:SUBMIT FORM=ACTION:http://api.captchasolutions.com/solve ATTR=VALUE:Send
wait seconds=5
TAG POS=6 TYPE=TD ATTR=* EXTRACT=TXT
SET !VAR1 {{!EXTRACT}}

TAB CLOSE
TAB T=1

TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:NoFormName ATTR=NAME:captcha CONTENT={{!var1}}

iMacros / Javascript Boilerplate

// iMacros Bootstrap - Write your macros with JavaScript.
// Be careful, you need to rename and set the extension of your macro to ".js".


// 1. Variables Initialization.


var variable1, variable2, variable3;

macro = "";

variable1 = "";

variable2 = "";

variable3 = "";


// 2. Built-in Variables & Macro Initialization.


macro += "CODE:" + "\n";

macro += "SET !TIMEOUT_STEP 2" + "\n";

macro += "SET !TIMEOUT_TAG 2" + "\n";

macro += "SET !TIMEOUT_PAGE 45" + "\n";

macro += "SET !ERRORIGNORE YES" + "\n";


// 3. Clear Cookies, Cache and Set a Proxy


macro += "CLEAR" + "\n";

macro += "PROXY ADDRESS=" + proxy + "\n";


// 4. Action 1.


macro += "TAB T=1" + "\n";

macro += "TAB CLOSEALLOTHERS" + "\n";

macro += "WAIT SECONDS=5" + "\n";

macro += "URL GOTO=https://gentlenode.com/" + "\n";


// 5. Action 2.


macro += "URL GOTO=http://journal.gentlenode.com/" + "\n";

macro += "WAIT SECONDS=5" + "\n";


// 7. Clear Browser.


macro += "WAIT SECONDS=1" + "\n";

macro += "CLEAR" + "\n";


// 8. Run the Macro.


iimDisplay("iMacro is now running.");

iimPlay(macro);

Autovisit LinkedIn Profile

// Auto-visit profiles on Linkedin with iMacros
// Configure your linkedin credentials, the group and your proxy if needed.
// To learn more about iMacros: http://bit.ly/1CImBoM


// 1. Variables Initialization


var macro, proxy, linkedinEmail, linkedinPassword, linkedinGroup, i, j;

macro = '';

proxy = '';

linkedinEmail = 'youremail@gmail.com';

linkedinPassword = 'password';

linkedinGroup = 'https://www.linkedin.com/groups?viewMembers=&gid=4631551&sik=1422235539201'


// 2. Macro Initialization


macro += 'CODE:' + '\n';

macro += 'SET !TIMEOUT_STEP 2' + '\n';

macro += 'SET !TIMEOUT_TAG 2' + '\n';

macro += 'SET !TIMEOUT_PAGE 45' + '\n';

macro += 'SET !ERRORIGNORE YES' + '\n';


// 3. Clear Cookies, Cache and Set a Proxy


macro += "CLEAR" + "\n";

if (proxy !== "") {
  macro += "PROXY ADDRESS=" + proxy + "\n";
}


// 4. Linkedin Sign In


macro += 'TAB T=1' + '\n';

macro += 'TAB CLOSEALLOTHERS' + '\n';

macro += 'WAIT SECONDS=1' + '\n';

macro += 'URL GOTO=https://www.linkedin.com/' + '\n';

macro += 'TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:login ATTR=NAME:session_key CONTENT=' + linkedinEmail + '\n';

macro += 'TAG POS=1 TYPE=INPUT:PASSWORD FORM=NAME:login ATTR=NAME:session_password CONTENT=' + linkedinPassword + '\n';

macro += 'WAIT SECONDS=2' + '\n';

macro += 'TAG POS=1 TYPE=INPUT:SUBMIT FORM=NAME:login ATTR=NAME:signin' + '\n';


// 5. Auto-Visit & Close Profiles


macro += 'WAIT SECONDS=2' + '\n';

macro += 'URL GOTO=' + linkedinGroup + '\n';

for (i = 2; i <= 25; i++) {

  for (j = 1; j <= 20; j++) {
    macro += 'EVENT TYPE=CLICK SELECTOR="HTML>BODY>DIV:nth-of-type(4)>DIV:nth-of-type(3)>DIV:nth-of-type(2)>DIV>UL>LI:nth-of-type(' + j + ')>SPAN>STRONG>A>IMG" BUTTON=0 MODIFIERS="meta"' + '\n';
    macro += 'WAIT SECONDS=2' + '\n';
  }

  macro += 'TAB T=2' + '\n';

  for (j = 1; j <= 20; j++) {
    macro += 'TAB CLOSE' + '\n';
  }

  macro += 'WAIT SECONDS=20' + '\n';
  macro += 'TAG POS=1 TYPE=A ATTR=TXT:' + i + '\n';

}


// 6. Run The Macro


iimDisplay("iMacro is now running. Let's hack growth.");

iimPlay(macro);

Perl Wrapper for iMacros Scripts

#!/usr/local/bin/perl

########################################################################################
# PERL WRAPPER FOR iMACRO SCRIPTS
# This code was written by me to be open source. There are no license restrictions.
# - Dave Grossman
########################################################################################
# Version 1.0   29 JAN 2008      Basic demo
########################################################################################

# Make sure to set iMacros browser -> Tools -> Options -> Paths -> FolderDownloads

use Win32::OLE;

$GlobalMacro = ''; # Global instance of iMacro referred to within the Macros below

sub Main
{
   # Local variables
   local $Macro, $RetCode, $Result;

   #--- iMacros starting --------------
   &StartMacroSession;

   &Macro_Startup;

   &MacroUrl("google.com");   # Go to the Google home page

   $Macro = <<"EOL";
TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:f ATTR=NAME:q CONTENT=iOpus
TAG POS=1 TYPE=INPUT:SUBMIT FORM=NAME:f ATTR=NAME:btnG
TAG POS=1 TYPE=A ATTR=HREF:http://www.iopus.com/
TAG POS=1 TYPE=A ATTR=HREF:http://www.iopus.com/imacros/
EOL

   ($RetCode, $Result) = &PlayMacro($Macro);   # Click through to iMacros

   ($RetCode, $Result) = &Macro_ExtractHtmlPage;   # Save the page
   &MacroSaveAs("temp.html");

   &EndMacroSession;
   #--- iMacros ended--------------

   print "$Result\n";   # Print the saved page

   print "\nALL DONE\n";
}

&Main;

exit;

########################################################################################
#--- Basic iMacro functions ----------------------------

sub StartMacroSession {
   $GlobalMacro = Win32::OLE->new('imacros') or die "Win32:OLE problem\n";
   $GlobalMacro->{Visible} = 1;
   $GlobalMacro->iimInit();
   print "\n***** iMacros started *****\n";
}

sub PlayMacro {
   local($Macro) = @_;
   local $RetCode = '';
   local $Result = '';
   $Macro =~ s/\s\n/\n/g;      # Eliminate trailing whitespace on each line
   $Macro =~ s/\n/\r\n/g;      # Change line terminator to vbNewLine
   $Macro =~ s/\r\r\n/\r\n/g;   # But be sure not to overdo it
   $RetCode = $GlobalMacro->iimPlay("CODE:$Macro") ;
   if($RetCode < 0) { $Result = $GlobalMacro->iimGetLastError(); }
   else { $Result = $GlobalMacro->iimGetLastExtract; }
   return ($RetCode, $Result);
}

sub EndMacroSession
{
   $GlobalMacro->iimExit();
   print "\n***** iMacros ended *****\n";
}

########################################################################################
# Higher level iMacro functions - all start with "Macro"
########################################################################################

# BACK - Like clicking the "Back" button on the browser
sub MacroBack { return &PlayMacro("BACK"); }

# FILTERIMAGES - Turns off images on subsequent pages
sub MacroFilterImages { return &PlayMacro("FILTER TYPE=IMAGES STATUS=ON"); }

# LOGIN
sub MacroLogin
{
   local($Url, $UserName, $Password) = @_;
   return &PlayMacro("ONLOGIN USER=$UserName PASSWORD=$Password\nURL GOTO=$Url");
}

# ONDOWNLOAD - Sets file store context for next URL
sub MacroOnDownload
{
   local($FileName) = @_;
   return &PlayMacro("ONDOWNLOAD FOLDER=* FILE=$FileName");
}

# PAUSE
sub MacroPause { return &PlayMacro("PAUSE"); }

# REFRESH
sub MacroRefresh { return &PlayMacro("REFRESH"); }

# SAVEAS - Save current page as html
sub MacroSaveAs   # Call WAIT before using this
{
   local($FileName) = @_;
   unlink $FileName;
   return &PlayMacro("SAVEAS TYPE=HTM FOLDER=* FILE=$FileName");
}

# TAB - Only use this browser tab
sub MacroTab { return &PlayMacro("TAB CLOSEALLOTHERS"); }

# TAG - Very complicated command with many parameters. See CheckTagString below for explanation.
sub MacroTag
{
   local($InputString) = @_;
   local $Macro = &CheckTagString($InputString);
   local ($RetCode, $Result) =  &PlayMacro($Macro);
   $Result =~ s/\[EXTRACT\]$//;
   return ($RetCode, $Result);
}

# URL - Go to URL
sub MacroUrl
{
   local($Url) = @_;
   return &PlayMacro("URL GOTO=$Url");
}

# WAIT
sub MacroWait { return &PlayMacro("WAIT SECONDS=#DOWNLOADCOMPLETE#"); }

########################################################################################
# Still higher level functions - all start with "Macro_"
########################################################################################

sub Macro_Startup
{
   return &PlayMacro("TAB T=1\nTAB CLOSEALLOTHERS");
}

sub Macro_ExtractHtmlPage
{
   $Macro = "TAG POS=1 TYPE=HTML ATTR=*:* EXTRACT=HTM";
   local ($RetCode, $Result) =  &PlayMacro($Macro);
   $Result =~ s/\[EXTRACT\]$//;
   return ($RetCode, $Result);
}

########################################################################################
# Utility function for TAG
########################################################################################
# Check TAG string to make sure it looks reasonable
#
# To choose an item on the page:
#   TYPE   :=X for the container <X>...</X>, e.g.,
#         =A follows links
#         =SELECT
#         =INPUT:TEXT
#         =INPUT:HIDDEN
#
#   ATTR
#      :=LHS:rhs to represent the attribute assignment LHS=rhs (&& boolean allowed), e.g.,
#         =TXT:NameOfLink
#         =HREF:UrlOfLink
#         =ID:Id
#         =VALUE:Value
#   POS
#         =CardinalNumberOfItem with specified TYPE and ATTR
#
# Or to choose a FORM
#   FORM
#      =NAME:NameOfLink
#
# To select from a SELECT list:
#   CONTENT
#      =EVENT:#SAVEITEM
#      =EVENT:#MOUSEOVER
#      =IndexInSELECTlist
#      =$NameInSELECTList
#      =%ValueInSELECTList
# To insert INPUT:
#   CONTENT
#      =ValueToInsert
#
# To extract data (see also SAVEAS):
#   EXTRACT
#      =TXT (eliminates all HTML)
#      =HTM (full html of item)
#      =HREF (URL of item)
sub CheckTagString
{
   local($InputString) = @_;

   # Make associative array of parms and their values
   local @Parms = split(/\s/, $InputString);
   local %Parms = ();
   local $i;
   for($i = 0; $i <= $#Parms; $i++)
   {
      local ($LHS,$RHS) = split(/=/, $Parms[$i]);
      $Parms{$LHS} = $RHS;
   }

   # Unpack the associative array
   local $OutputString = 'TAG';
   local $Error = 0;
   if(exists($Parms{'TYPE'}))
   {
      local $Type = $Parms{'TYPE'};
      $OutputString .= " TYPE=$Type";
       $Pos =~ s/\s//;
      if(length($Type) < 1 || $Type ne $Parms{'TYPE'}) { $Error += 1; }
   }
   if(exists($Parms{'POS'}))
   {
      local $Pos = $Parms{'POS'};
      $OutputString .= " POS=$Pos";
       $Pos =~ tr/0-9//cd;
      if($Pos <= 0 || $Pos ne $Parms{'POS'}) { $Error += 2; }
   }
   if(exists($Parms{'ATTR'}))
   {
      local $Attr = $Parms{'ATTR'};
      $OutputString .= " ATTR=$Attr";
      $Attr =~ s/\s//;
      if($Attr ne $Parms{'ATTR'}) { $Error += 4; }
      local @Attr = split(/&&/, $Attr);
      local $i;
      for($i = 0; $i <= $#Attr; $i++)
      {
         local @AttrSubcommand = split(/:/, $Attr[$i]);
         unless (($AttrSubcommand[0] eq 'TXT' ||
            $AttrSubcommand[0] eq 'HREF' ||
            $AttrSubcommand[0] eq 'ID' ||
            $AttrSubcommand[0] eq 'VALUE' ||
            $AttrSubcommand[0] eq '*')
            && length($AttrSubcommand[1]) > 0)
         { $Error += 8; }
      }
   }
   if(exists($Parms{'FORM'}))
   {
      local $Form = $Parms{'FORM'};
      $OutputString .= " FORM=$Form";
      local @Form = split(/:/, $Form);
      unless ($Form[0] eq 'NAME' && length($Form[1]) > 0) { $Error += 16; }
   }
   if(exists($Parms{'CONTENT'}))
   {
      local $Content = $Parms{'CONTENT'};
      $OutputString .= " CONTENT=$Content";
      local $Leng = length($Content);
      unless((substr($Content, 0, 6) eq 'EVENT:' && $L > 6) || $L > 0) { $Error += 32; }
   }
   if(exists($Parms{'EXTRACT'}))
   {
      local $Extract = $Parms{'EXTRACT'};
      $OutputString .= " EXTRACT=$Extract";
      unless($Extract eq 'TXT' || $Extract eq 'HTM' || $Extract eq 'HREF') { $Error += 64; }
   }

   if($Error > 0) { die "Fatal error $Error in CheckTagString for InputString=$InputString\n"; }
   return $OutputString;
}

License

Windows License 1/10/16

Key DVT7ZV73M7XZCW4WIN85AFB5X4J5G5 DVTDPSDQBM4TBPSB55ZZY3RHVADED5 DVTS6KPJJBJIU42M3ZDK4CSIU3U2H5 DVTVRVEB6DCBYNHC63BN86RUDC3MB5 DVTVS5SQKXXP8A3Q72YBN7GRTPFJG5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.