Documente Academic
Documente Profesional
Documente Cultură
BrowserAutomationiMacros
BrowserAutomation
FromiMacros
Contents
1iMacrosAutomation
1.1Play(Loop)Button
1.2Shortcuts
1.3CommandLineInterfaceandBatchFiles
1.3.1Checkonthereturnvalueatbatchlevel
1.4ScheduleTasks
2DialogManager
2.1Login
2.2Javascript
2.3WebPageDialogs
2.4Print
2.5SecurityDialogs
2.6Certificates
2.7PageErrors
3SavingWebSites
3.1WebSiteScreenshot
3.2SaveWebsiteElements
3.2.1DownloadFiles
3.2.2SaveItem
3.2.3SaveElementScreenshot
3.2.4SaveTargetAs
4ProxyServer
5ErrorHandling
5.1Macrolevel
5.2Batchfilelevel
5.3Scriptinglevel
5.4ErrorCodes
iMacrosAutomation
ManytasksyoucanautomateusingiMacrosrequiremultipleorregularexecution,likefillinginanonlineform
withmanydatasetsorregularlydownloadingastatusreport.iMacroshasseveralfeaturestosupportthiskind
ofautomation:
Play(Loop)Button[AllEditions]
Shortcuts[AllEditions]
CommandlineinterfaceandBatchFiles[PROandSCRIPTINGEditions]
ScheduleTasks[PROandSCRIPTINGEditions]
ScriptingInterface[SCRIPTINGEdition]PleaseseetheWebScriptingChapter
Play(Loop)Button
http://wiki.imacros.net/Browser_Automation
1/10
11/25/2016
BrowserAutomationiMacros
ThePlay(Loop)willrepeatthemacrouptothemaximumloopnumberspecified.Note
thatyoucansetthe!LOOPvariableinsidethemacro,soitdoesnotneedtostartat1.
Shortcuts
InsteadofopeningtheiMacrosBrowser,markingthemacroyouwanttoplayand
clickingtheplaybutton,youcancreateashortcuttostartiMacrosandautomaticallyruna
predefinedmacro.
Tocreateashortcut:
Locateimacros.exe.ThisistheiMacrosBrowser,typicallylocatedinC:\ProgramFiles\iMacros.
Rightclickonimacros.exeandselectthe"CreateaShortcut"option.
AnewfilecalledShortcuttoimacros.lnkwillbecreatedinthesamefolder.Selectthefileandrightclickon
it.
Select"Properties"andthefollowingdialogwillcomeup:
IntheboxTargetyoufindanentrysimilartoC:\Program
Files\iMacros\Ipswitch\iMacros\imacros.exe.
Changethisto"C:\ProgramFiles\Ipswitch\iMacros\imacros.exe"macro
yourmacronoexit.Youmustusequotationmarksaroundthecommand.
Note:Donotchangethepathinthebox"Startin".
ShortcutProperties
Ready!Youcannowmovethisshortcuttoaconvenientplace(liketheDesktop)
andstartiMacrosbysimplydoubleclickingontheshortcut.
Foradetailedexplanationofthevariouscommandlineoptionspleaseseethe
sectiononcommandlineswitches.
CommandLineInterfaceandBatchFiles
Relatedexamplebatch:Examples\BatchFiles
TheiMacrosBrowser(iMacros.exe)andtheiMacrosSidebarforIE(iMacros.Sidebar.exe)includedinthe
StandardandEnterpriseEditionssupportseveralcommandlineoptionsthatcontrolthebehaviourofthe
browser.Also,thebrowsercanbecalledfrombatchfiles.Batchfilesareverysimpleprogramsthatallowsome
structurestheiMacromacrolanguagedoesnotsupportdirectly.Suchstructuresincludeconditional
programming(if...then...else...),loops(for...do...)andfileinput/output.Theyconsistofaseriesofcommands,
canbecreatedandeditedbyanyeditor(e.g.Notepad)andhavethefileending.bat.Batchfilescanbestartedin
thestandardway,bydoubleclickingonthefile,butalsothroughtheScheduler(SeetheScheduleTaskssection
onthispage),whichisapartoftheWindowsoperatingsystembydefault.
Pleasenotethatfileshortcutscanbelookedatassimplyabatchfilethatconsistsofonlyoneline:the
commandlinecallingtheprogram.
ThemostimportantpartofabatchfilethatstartsiMacrosisthecommandlinetostartthebrowser.As
mentionedbefore,thiscommandsupportsseveralcommandlineoptionsthatcontrolthebehaviourofthe
browser.Thegeneralcommandlinesyntaxis
imacroscommand_line_switch1switch_value1command_line_switch2switch_value2...
http://wiki.imacros.net/Browser_Automation
2/10
11/25/2016
BrowserAutomationiMacros
AftercompletingthemacrotheiMacrosBrowserautomaticallystopsandcloses.Tokeepthebrowseropen,use
thenoexitswitch.
YoucannowusebatchfilestoconvenientlyexecuteseveraliMacrosinasequence:
echoStartiMacrosbatchfile
imacrosmacroFormExampleMacro
imacrosmacroCheck_Altavista
imacrosmacroBuy_Now!
echoDone!
Intheabovemacrothebatchcommandechoisusedtoprintmessagestothestandardoutput.
Otherimportantcommandlineswitchesarethosesettingvariables.Withthecommandlineswitch
var_varnameyoucancreateyourowncustomvariables.Imagine,youwanttocallamacro(searchEngine.iim)
thatentersthecontentofthevariable"keywords"intoasearchengineandpressessubmit.Youcansetthe
searchvalueviathecommandline:
imacrosmacrosearchEnginevar_keywords"iOpusiMacros"
Notethatthenameofthevariableafterthevar_prefixmustcorrespondtothevariablenameusedinthemacro:
'searchEngine.iim
URLGOTO=http://www.google.com/search?q={{keywords}}
Forsettingmorevariables,youcansimplyaddmorevar_varnameparameters:
imacrosmacrosearchEnginevar_keywords"iOpusiMacros"var_date05/06/2008
Checkonthereturnvalueatbatchlevel
TheiMacrosexecutableimacros.exesetsthepredefinedbatchfilevariableERRORLEVEL.Thevalueiseither
1ifthemacrowascompletedsuccessfullyornegativeifanerrorwasencountered.ERRORLEVELisused
almostexclusivelywithaconditionalconstruct,e.g.:
imacrosmacrosearchEnginevar_SEARCHSTRINGiOpus[SP]iMacros
IFNOT%ERRORLEVEL%==1ECHOProblemencountered
Formoredetailspleaseseetheincludedexamplebatchfile"ExampleErrorlevel.bat".
PleasenoteanimportantrestrictionhereisthateachcalltoiMacrosrunsinaseparatebrowserthatisclosed
whenthemacrofinishes.Thismeansyoucannothavesubsequentmacroscontinuingfromwheretheprevious
onefinished.Tohaveamacrologintoawebsiteandsecondmacroloopthroughthesiteyouneedtousethe
scriptinginterface.
ScheduleTasks
iMacrosisfullycompatiblewithallstandardtaskschedulers,includingthebuiltinMicrosoftWindowsTask
Scheduler(pleaseseethisarticleforimportanttipsaboutschedulingmacros).
TheMicrosoftTaskSchedulerispartofyourWindowssystem.It"hides"inthe"ControlPanel"folder,which
islocatedinthe"MyComputer"folderonyourdesktop.
http://wiki.imacros.net/Browser_Automation
3/10
11/25/2016
BrowserAutomationiMacros
ByusingTaskScheduler,youcanscheduletaskssuchasiMacrosorsystemtoolsliketheDiskDefragmenterto
runatadefinedtimethatismostconvenientforyou.TheTaskSchedulerstartseachtimeyoustartWindows
andrunsinthebackground,checkingifanyscheduledtaskisdue.WithTaskScheduler,youcanschedulea
tasktorundaily,weekly,monthly,oratcertaintimessuchassystemstartup.
YoucanaccessthisfromtheStartMenuandclickingonSettingsandthenControlPaneltoScheduledTasks.
FormoreinformationpleaseseetheTaskSchedulersamplecodechapter.
DialogManager
TheDialogManagerallowsyoutomanageallthosepesky
dialogsthatappearwithInternetExplorerfromtimeto
time.BecausetheiMacrosBrowseremulatesInternet
ExplorerthesamedialogsappearintheiMacrosBrowser
too.
Important:YoucaninserttheONDIALOG,ONLOGIN
(etc.)dialogcommandsanywhereinthemacrobutithasto
bebeforetheTAGcommandthattriggersthedialog.
Thedialogmanagerisalwaysenabledandactive.Ifsome
dialogsquicklydisappearduringreplay,itisbecausethe
Dialogmanagerclosesthemautomatically.
iMacroshandlesallthesedialogs
Login
iMacrosfillsalllogindialogsforyouusingtheONLOGINcommand.Thepasswordisstoredwiththemethod
youselectedontheSecuritytaboftheOptionsdialog.Moredetailsaboutthedifferentpasswordstorage
optionscanbefoundhere.
Javascript
(Relatedexamplemacro:DemoJavascriptDialog)
iMacroshandlesallJavascriptdialogboxesforyouusingtheONDIALOGcommand.
YoucanevenextractthetextofadialogbyaddingSET!EXTRACTDIALOGYEStoyourmacro.
WebPageDialogs
(Relatedexamplemacro:DemoWebPageDialog)
WebpagedialogsaresimilartoJavascriptdialogs,excepttheydisplayHTMLcontent.iMacroscancontrol
themusingtheONWEBPAGEDIALOGcommand.Sincewebpagedialogscancontainanynumberofbuttons
orboxesyoucanautomatethembysendingaspecificlistofkeyboardcommandstothem.Forexample
"KEYS=Hello{ENTER}{CLOSE}"willentertheword"Hello"onthedialog,pressENTERkeyandthenclose
thedialog.
http://wiki.imacros.net/Browser_Automation
4/10
11/25/2016
BrowserAutomationiMacros
Duringreplay"ONWEBPAGEDIALOGKEYS={WAIT<sp>2}{CLOSE}"isactivebydefaulttoclose
unwantedaddialogs.
Notes:
1.WebpagedialogsarenotnormalHTMLbrowserwindows.Thereforetheydonotopeninaseparatetab,
butpopupinfrontofthecurrentwindow.
2.Webpagedialogsareeithermodalormodeless.Amodaldialogboxmustbeclosedbeforeyoucan
continueworkingwiththerestofthewebapplication.TheONWEBPAGEDIALOGcanautomateboth
typesofwebpagedialogs.FormodelesswebpagedialogsyoucanusealsousetheDirectScreen
Technology.
3.Therearealsootheroptionstoautomatewebpagedialogs.
Print
(Relatedexamplemacro:DemoPrint)
Thedialogmanagerworkswiththeprintdialog.FormoredetailspleaseseetheONPRINTeventandthe
PRINTcommand.
SecurityDialogs
Securitydialogscanoccuronmanysecurewebsites.TheiMacrosDialogManagerautomaticallyclicksthe
securitydialogboxessoyourmacrosarenotinterrupted.ThisisdoneusingtheONSECURITYDIALOG
command.
BydefaultthesettingsareBUTTON=YESandCONTINUE=YES.Thesesettingsareactiveevenwithoutan
ONSECURITYDIALOGcommandinyourmacro.
TheSecureandNonSecureItemsWarningMessageisnothandledbytheDialogManager,asthisisanoptional
messagethatcanbedisabledintheInternetExplorer(IE)settings.TheIEsettingsalsoapplytotheiMacros
Browser.
Certificates
http://wiki.imacros.net/Browser_Automation
5/10
11/25/2016
BrowserAutomationiMacros
Somesecurewebpagesaskyoutoselectaclientsidecertificate.Thedialogmanagercandothisforyouusing
theONCERTIFICATEDIALOGcommand.
PageErrors
(Relatedexamplemacro:DemoOnError)
Pagescripterrorscanoccuronmanywebsitesforavarietyofreasons.TheiMacrosDialogManager
automaticallyclickstheInternetExplorererrordialogboxessoyourmacrosarenotinterruptedbyscripterrors!
ThisisdoneusingtheONERRORDIALOGcommand.
BydefaultthesettingsareBUTTON=YESandCONTINUE=YES.Thesesettingsareactiveevenwithoutan
ONERRORDIALOGinyourmacro.
FormoredetailspleaseseeIsthereanywaytoverifyifanyjavascripterrorshavebeenthrown?.
SavingWebSites
(Relatedexamplemacro:DemoArchivePage,DemoSaveAs)
iMacrosautomaticallydownloadsandsaveswebpagesforyou.UsetheTasksdropdown
andselect"SavePage","SaveScreenshot",or"SaveExtractedData".iMacroswillthen
insertaSAVEAScommandinthemacro,holdinginformationabouttheformatandthe
locationwherethefileissaved.Thedefaultlocationisinthedownloads\directoryofyouriMacrosinstallation.
Thiscommandisveryeasilytweakedafterthemacrohasbeenrecordedtofityourneeds.
Youhavedifferentoptionsastowhichformatyouwishusetosavethecurrentlydisplayedwebpage.These
optionsare
CPL
Thecompletewebpageissaved.Thefilesandimagesaresavedseparatelyandstoredinafolder.
MHT
Thewebpageplusimagesaresavedinasinglefile(WebArchive).
HTM
Thewebpagesourceissavedwithnoimages.IfthepagehasframesallframedHTMLpagesaresaved
automatically.
TXT
OnlythewebpagetextissavedallHTMLtagsareomitted.
PNG
Ascreenshotofthewebpageissaved.Use"SaveScreenshot"torecordthiscommand.
EXTRACT
Thevalueofthevariable!EXTRACTissavedinCSVformat.Use"SaveExtractedData"torecordthis
command.
WebSiteScreenshot
(Relatedexamplemacro:DemoTakeScreenshot)
http://wiki.imacros.net/Browser_Automation
6/10
11/25/2016
BrowserAutomationiMacros
TheiMacrosBrowsercanautomaticallytakescreenshotsofwebpages.This
includesthepart"belowthefold",i.e.iMacrostakesthescreenshotofthe
entirewebpage,nomatterthelength,evenifitscrollsoffscreen!
Totakeawebpagescreenshotusethe"Tasks"option"SaveScreenshot"
whilerecordingamacro,orinsertaSAVEASTYPE=PNGcommandintothe
macrolikeinthisexample(fortheFOLDERandFILEsettingsseethe
documentationfortheSAVEAScommand):
SAVEASTYPE=PNGFOLDER=*FILE=My_Screenshot.png
iMacrosusesthestandard,losslessPNGformat.Thisfileformatcanbeused
withanyimageeditor.
SaveWebsiteElements
iMacroscaninterceptfiledownloadsandevendownloadpicturesandother
elementsfromthewebsiteyouarevisiting.
DownloadFiles
(Relatedexamplemacro:DemoDownload)
Wheneverafiledownloadisinitiated,InternetExplorerwillpresentyouwith
thedialogshown.Thisdialogallowsyoutoselectwantyouwouldliketodo
withthefile.Ifyouchoosetosaveititwillalsoaskyouforthefilenameand
location.
iMacrostakesscreenshotsof
theentirewebpage,nomatter
whatlength
DownloadsarecontrolledbytheONDOWNLOADcommand.Ithastwo
parametersthatcontrolthefilenameandthefolderinwhichtosavethefile.It
mustappearbeforethemacrocommandthatstartsthedownload.
Note:Thegeneralwebpagetimeoutalsoappliestodownloads.Somakesurethat
thetimeoutvalueislongenoughtocoverthecompletedownloadtime.Ifneeded
youcanalsoincreasethetimeoutvaluemanuallyinsidethemacrowiththe
SET!TIMEOUT_PAGEcommand.
SaveDialoghandledby
iMacros
SaveItem
(Relatedexamplemacro:DemoImageDownload)
ThetypicaluseforSAVEITEMisautomatedimagedownloading.Todownloadanimageswitchtorecording
mode,navigatetothepageandpress"ExtractImage"intherecordingtab.TheImageExtractionWizardopens
andwhateverimageyouselectfromnowonwillbedisplayedonthepreview.TheproperTAGcommand,e.g.
TAGPOS=1TYPE=IMGATTR=HREF:http://imacros.net/wpcontent/uploads/2013/12/imacrosipswitch.pngCONTENT=EVENT:SAVEITEM
willbeautomaticallygeneratedand,ifyouaresatisfiedwiththefinalresult,youcanaddthecommandstothe
macrobeingrecorded.Youmayalsochangethefinalfolderlocationandfilename.
Youcanalsocreatedownloadtaglinesmanually.Duringrecordingsimplyclickonthewanteditemandadd
"CONTENT=EVENT:SAVEITEM"tothegeneratedTAGlineinaneditorofyourchoice.
http://wiki.imacros.net/Browser_Automation
7/10
11/25/2016
BrowserAutomationiMacros
ThedownloadedfilesarecopiedfromInternetExplorercacheto
theiMacrosdownloaddirectory.UsetheONDOWNLOAD
commandtospecifyanameandlocationforthedownloaded
image.
Somewebsitesuse"tricks"tomakeimagedownloadstricky.But
notforiMacros:Youcanalso"takeasceenshot"oftheimage
instead.Thishastheadvantagethatitworkswitheveryimage,but
doesdownloadtheoriginalfile.See
SAVE_ELEMENT_SCREENSHOT
Usetheimageextractionwizardtocreate
TAGcommandsforsavingimagesfroma
website.
SaveElementScreenshot
(Relatedexamplemacro:DemoImageDownload)
ThiscommandissimilartoSAVEITEM,whichisthedefault
commandforimagedownloading.However,unlikeSAVEITEMitdoesnotaccesstheimagewhichwas
storedinIEcachebutitmakesa"screenshot"oftheimageelement.Thiswaythesavedimageisexactly
theonedisplayedonthebrowser.Thiscanbeanadvantageonwebsiteswhereimagesareconstructed"onthe
fly".
ForelementsoftypeIMG,youcanusetheImageExtractionWizardtoproducetherightTAGand
ONDOWNLOADcommandsforusingtheSAVE_ELEMENT_SCREENSHOTbychoosing"Takescreenshot
ofimage"asMethod(radiobutton).HoweverSAVE_ELEMENT_SCREENSHOTcanbeusedonanyelement
type,andinthiscase,youneedtomanuallyeditarecordedmacro.Clickontheelementyouwishtodownload
andiMacroswillproduceacommandlike
TAGPOS=1TYPE=H2ATTR=TXT:Online<SP>Store
Thiswouldsimulateamouseclickonthelink.Sincethisisnotwhatwewantweneedtoeditthemacroand
add"CONTENT=EVENT:SAVE_ELEMENT_SCREENSHOT"totherecordedTAGcommand.Youwillthen
have
TAGPOS=1TYPE=H2ATTR=TXT:Online<SP>StoreCONTENT=EVENT:SAVE_ELEMENT_SCREENSHOT
TheimagefilesproducedinthiswayarealwaysinthePNGformat.UsetheONDOWNLOADcommandto
specifythenameandlocationforthedownloadedimage,howeveryoucannotchangetheimageformat,even
youuseadifferentfileextension.
SaveTargetAs
(Relatedexamplemacro:DemoSaveTargetAs)
Todownloadanykindofwebcontentsuchas.WVMor.AVIvideos,soundfilessuchas.MP3,ordocuments
suchas.PDF,firstclickonthelinkthatconnectstotheitem.Inthecaseofa.PDFfilesuchalinkistypically
called"Opendocument"orforavideofile"Showvideo".iMacrosrecordsaTAGcommand:
TAGPOS=1TYPE=BATTR=TXT:Open<SP>PDF<SP>Document
Thiswouldsimulateamouseclickonthelink.Thisisnotwhatwewant,weneedacommandsimilartothe
rightclickcommand"SaveTargetAs"inInternetExplorer.Thiscanbeachievedbyeditingthemacroand
adding"CONTENT=EVENT:SAVETARGETAS"totherecordednormalTAGcommand.Youwillthenhave:
http://wiki.imacros.net/Browser_Automation
8/10
11/25/2016
BrowserAutomationiMacros
TAGPOS=1TYPE=BATTR=TXT:Open<SP>PDF<SP>DocumentCONTENT=EVENT:SAVETARGETAS
ThefilesdownloadedinthiswayarecopiedtotheiMacrosdownloaddirectorybydefault.Youcanusethe
ONDOWNLOADcommandtospecifythenameandlocationforthedownloadedimage.
ProxyServer
ThePROXYcommandinstructstheiMacrosBrowsertoconnectto
theInternetthroughaproxyserverbyusingthesettingsyouspecify.
Aproxyserveractsasanintermediarybetweenyourinternal
network(intranet)andtheInternet,retrievingfilesfromremoteWeb
servers.Youcandefineaspecificproxyserverforeachmacro.Each
runninginstanceoftheiMacrosBrowsercanhaveitsownproxy
server.
ProxyServer
Ifaproxyserverisactivetheword"PROXY:"isdisplayedinthestatusbar.
ThefollowingexamplesshowthegeneraluseofthePROXYcommand.E.g.,thiscommandusesalocalproxy
serverforbothhttpandhttpsattheaddress192.1.8.1andtheportnumber8080.Sincenobypassisspecified
thedefaultsettingsareused.
PROXYADDRESS=192.1.8.1:8080
Thiscommandspecifiestwodifferentproxyserverforthehttpandhttpsprotocol.Nobypassisdefinedso
iMacrosusestheseproxyserversevenforlocaladdresses.
PROXYADDRESS=http=192.1.8.1:8080<SP>https=192.1.8.2:8080BYPASS=NULL
Touseaproxyserverataddress66.98.229.110,buttonotuseitforURLsincludingtheword"iMacros"use
PROXYADDRESS=66.98.229.110:8080BYPASS=*imacros*
Youcanalsousethesamecommand,butwithURLinsteadofIPaddress.
PROXYADDRESS=imacros.net:8080BYPASS=*imacros*
ErrorHandling
iMacroscanhandleallerrorsthatoccurduringreplay.Sincereplayofmacroscanbeachievedbydifferent
meanstheerrormanagementisdifferentaswell.
Macrolevel
YoucandecidetoignoremacroerrorswithSET!ERRORIGNOREYES.
YoucanalsoperformsophisticatedlogicandgenerateanerrorconditionusingtheEVALcommand.
Batchfilelevel
http://wiki.imacros.net/Browser_Automation
9/10
11/25/2016
BrowserAutomationiMacros
Thevariable%ERRORLEVEL%isfilledafterthemacroiscompleted.Valuesgreaterthanzeroindicate
success,negativevaluesindicateaproblem.
RelatedExampleBatchFile:ExampleErrorlevel.bat
Scriptinglevel
PleaseseethechapteronWebScriptingforsophisticatederrorhandlingviatheScriptingInterface.
ErrorCodes
SeeErrorandReturnCodes
Generalclassification:
1xx:Userinteraction
8xx:ErrorsspecifictotheFirefoxandChromeAddOns
9xx:ErrorsspecifictotheFirefoxandChromeAddOns
1xxx:iMacrosBrowserandIEpluginreplayerrors
AdetailedlistofErrorandReturnCodesisavailable.
Retrievedfrom"http://wiki.imacros.net/index.php?title=Browser_Automation&oldid=9871"
Thispagewaslastmodifiedon15October2015,at15:56.
Thispagehasbeenaccessed708,573times.
http://wiki.imacros.net/Browser_Automation
10/10