Imacros пропустить ошибку

Переменная iMacros !ERRORIGNORE

Если переменная !ERRORIGNORE установлена со значением YES, тогда iMacros будет игнорировать возникающие ошибки. Макрос продолжает выполняться, даже если одна или несколько команд не были выполнены. Принимаемые значения: YES | NO.

Совет: Эту переменную можно использовать для того, чтобы iMacros пропускал несуществующие элементы страницы (TAG), с ее помощью можно сократить время ожидания невидимого / несуществующего на странице TAG элемента , обработка которого записана в макросе. По умолчанию 6 секунд. Чтобы изменить время ожидания, используйте !TIMEOUT_STEP.

Синтаксис:

SET !ERRORIGNORE YES

Задается:

× Внутренняя переменная

✓ Командой SET

«Внутренняя переменная» означает, что сам iMacros устанавливает значение данной переменной во время выполнения макроса. SET означает, что пользователь может установить это значение с помощью команды SET при редактировании макроса.

Пример:

Использование переменной !ERRORIGNORE iMacros для пропуска ошибок в части кода:

SET !TIMEOUT_STEP 1 SET !ERRORIGNORE YES ‘Команды которые иногда не работают (элементы не найдены)

TAG… TAG… ‘Возвращаем значения по умолчанию

SET !ERRORIGNORE NO SET !TIMEOUT_STEP 6

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

Value iMacros 2021.0 Firefox Chrome iMacros Browser

YES|NO

Set By

[ ] Internal

[X] SET

Internal means that the iMacros program itself sets the value of the variable during program run. SET means that the user can set this value via the SET command inside a macro.

Tip: If you use this command to skip not-existing (only sometimes existing) web page elements (TAG), then it can be useful to reduce the default time iMacros waits for a missing TAG to appear (6 seconds). Use the !TIMEOUT_STEP paramter for this.

Note: SET !ERRORIGNORE YES does not yet ignore the EVAL command error in iMacros for Firefox 10 (as it is in iMacros Browser).

Examples

SET !TIMEOUT_STEP 1
SET !ERRORIGNORE YES
'Commands that fail sometimes (element missing)
TAG...
TAG...
'Restore defaults
SET !ERRORIGNORE NO
SET !TIMEOUT_STEP 6

  • «OR» function for buttons?
  • Use one of two links (depending on which one is there)
  • Ignore the error and keep runing code

See Also

Error Handling, !TIMEOUT_STEP

I have 1000+ URLs that I want to scrape to retrieve the title value from the HTML. After trying different things, I ultimately used iMacros scripts, which I don’t know anything about. Nonetheless, I managed to make a script after reading guides.

My script is working perfectly but has a problem: When leeching URLs titles, if it encounters an HTTP error (e.g. dead link, forbidden page, etc), it crashes with an error message like this one:

Error -1350: Error loading page. Http status 403. Line 4: URL GOTO=http://url.com

Instead of crashing when the script encounters these errors, I would like it to simply skip the URL and continue running. How can I modify my script to do this? Here is my script:

VERSION BUILD=9002379
TAB T=1
TAB CLOSEALLOTHERS
URL GOTO=http://google.com/
ADD !EXTRACT {{!URLCURRENT}}
TAG POS=1 TYPE=TITLE ATTR=* EXTRACT=TXT
SAVEAS TYPE=EXTRACT FOLDER=d:/ FILE=links.txt
SET !EXTRACT_TEST_POPUP NO

Output:

http://google.com/,Google

I would also like to replace the comma after the URL in the output with a semicolon.

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

Value iMacros 2021.0 Firefox Chrome iMacros Browser

YES|NO

Set By

[ ] Internal

[X] SET

Internal means that the iMacros program itself sets the value of the variable during program run. SET means that the user can set this value via the SET command inside a macro.

Tip: If you use this command to skip not-existing (only sometimes existing) web page elements (TAG), then it can be useful to reduce the default time iMacros waits for a missing TAG to appear (6 seconds). Use the !TIMEOUT_STEP paramter for this.

Note: SET !ERRORIGNORE YES does not yet ignore the EVAL command error in iMacros for Firefox 10 (as it is in iMacros Browser).

Examples

SET !TIMEOUT_STEP 1
SET !ERRORIGNORE YES
'Commands that fail sometimes (element missing)
TAG...
TAG...
'Restore defaults
SET !ERRORIGNORE NO
SET !TIMEOUT_STEP 6
  • «OR» function for buttons?
  • Use one of two links (depending on which one is there)
  • Ignore the error and keep runing code

See Also

Error Handling, !TIMEOUT_STEP

I have 1000+ URLs that I want to scrape to retrieve the title value from the HTML. After trying different things, I ultimately used iMacros scripts, which I don’t know anything about. Nonetheless, I managed to make a script after reading guides.

My script is working perfectly but has a problem: When leeching URLs titles, if it encounters an HTTP error (e.g. dead link, forbidden page, etc), it crashes with an error message like this one:

Error -1350: Error loading page. Http status 403. Line 4: URL GOTO=http://url.com

Instead of crashing when the script encounters these errors, I would like it to simply skip the URL and continue running. How can I modify my script to do this? Here is my script:

VERSION BUILD=9002379
TAB T=1
TAB CLOSEALLOTHERS
URL GOTO=http://google.com/
ADD !EXTRACT {{!URLCURRENT}}
TAG POS=1 TYPE=TITLE ATTR=* EXTRACT=TXT
SAVEAS TYPE=EXTRACT FOLDER=d:/ FILE=links.txt
SET !EXTRACT_TEST_POPUP NO

Output:

http://google.com/,Google

I would also like to replace the comma after the URL in the output with a semicolon.

iMacro CheatSheet — Command Reference

  • http://wiki.imacros.net/Command_Reference
  • http://wiki.imacros.net/iMacros_for_Firefox#Javascript_Scripting_Interface

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('u00EFu00BBu00BF', 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 "$Resultn";   # Print the saved page

   print "nALL DONEn";
}

&Main;

exit;

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

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

sub PlayMacro {
   local($Macro) = @_;
   local $RetCode = '';
   local $Result = '';
   $Macro =~ s/sn/n/g;      # Eliminate trailing whitespace on each line
   $Macro =~ s/n/rn/g;      # Change line terminator to vbNewLine
   $Macro =~ s/rrn/rn/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=$PasswordnURL 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=1nTAB 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=$InputStringn"; }
   return $OutputString;
}

License

Windows License 1/10/16

Key
DVT7ZV73M7XZCW4WIN85AFB5X4J5G5
DVTDPSDQBM4TBPSB55ZZY3RHVADED5
DVTS6KPJJBJIU42M3ZDK4CSIU3U2H5
DVTVRVEB6DCBYNHC63BN86RUDC3MB5
DVTVS5SQKXXP8A3Q72YBN7GRTPFJG5


WMmail.ru - сервис почтовых рассылок

Содержание:

!CLIPBOARD

!ERRORIGNORE

!EXTRACT

!NOW

!REPLAYSPEED

!TIMEOUT

!VAR1, !VAR2, !VAR3

!CLIPBOARD

Внутренняя переменная !CLIPBOARD содержит значение из буфера обмена.

Пример:

как в макросе прописать вставку в поле ввода данных из буфера обмена?

TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:formuzd ATTR=ID:zd_name CONTENT={{!CLIPBOARD}}

!ERRORIGNORE

Внутренняя переменная imacros -игнорирование ошибок,

принимает значения: YES|NO (по умолчанию NO ).

!ERRORIGNORE отвечает за игнор ошибок скрипта, даже если одна или несколько команд не выполнены и передали ошибку, imacros продолжит выполнение скрипта.

Пример:

SET !ERRORIGNORE YES ошибки игнорируются.

SET !ERRORIGNORE NO ошибки не игнорируются, после ошибки выполнение скрипта прекращается.

Пример:

VERSION BUILD=7031111 RECORDER=FX

SET !ERRORIGNORE YES

SET !ERRORCONTINUE YES    

TAB T=1    

TAB CLOSEALLOTHERS 

!EXTRACT

Внутренняя переменная !EXTRACT позволяет извлечь данные из страницы с возможностью математических операций сложения или вычитания с этими данными с помощью команды ADD.

Пример:

TAG POS=3 TYPE=B ATTR=TXT:* EXTRACT=TXT — извлекаем данные,

ADD !EXTRACT {{!COL1}} — добавляем данные из переменной !COL1,

SET !EXTRACT NULL  — обнуляем переменную.

!NOW

Внутренняя переменная содержит текущее время и дату. Для того, чтобы отформатировать даты и времени вы можете использовать следующие коды формата, которые нужно добавить к переменной после двоеточия

!NOW:yyyy-mm-dd<SP>hhh<SP>nnmin

Формат кода

Формат кодов чувствительны к регистру. Формат кода может включать пробелы, но не забудьте использовать <SP> для пробелов

dd — Показывает день 2-значное число (01 — 31).

mm — Отображение месяца в виде 2-значное число (01 — 12).

yy — Показывает год, как 2-значное число (00 — 99).

yyyy — Показывает год, как 4-значное число (100 — 9666).

hh — Отображает час в виде 2-значное число (00 — 23).

nn — Отображение минут в виде 2-значное число (00 — 59).

ss — Отображает секунды в виде 2-значный номер (00 — 59).

Пример:

VERSION BUILD=7361445

TAB T=1

TAB CLOSEALLOTHERS

URL GOTO=http://www.amazon.com/

TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:site-search ATTR=ID:twotabsearchtextbox CONTENT=»!NOW:yyyy/mm/dd_hhnn test»

!REPLAYSPEED

Внутренняя переменная !REPLAYSPEED устанавливает скорость воспроизведения макроса быстрой, средней или медленной. Быстрая скорость воспроизведения означает, что нет задержки между каждым шагом. Средняя добавляет задержки в 1 секунду, а медленная в 2 секунды между каждой командой. Эта переменная отменяет глобальную скорость воспроизведения установленную в настройках.

Значения переменной — FAST|MEDIUM|SLOW

Пример:

SET !REPLAYSPEED FAST

!TIMEOUT

Внутренняя переменная !TIMEOUT устанавливает значение таймаута в секундах. Если в заданный промежуток времени действие не выполнено, !TIMEOUT сообщит об ошибке, выполнение скрипта завершиться! По умолчанию в imacros задан таймаут 60 секунд. Значение переменной !TIMEOUT автоматически устанавливает значение переменной !LOADCHECK = 1/10 !TIMEOUT.

Значением переменной может быть любое целое число >0

Пример:

SET !TIMEOUT 100

!VAR1, !VAR2, !VAR3

Все внутренние переменные в imacros имеют префикс «!».

!VAR1, !VAR2, !VAR3 это внутренние переменные для произвольного использования, им можно присвоить как числовое так и строчное значение.

Чтобы установить значение переменной необходимо использовать команду SET:

SET !VAR1 154

Для использования значения переменной, заключите её в двойные фигурные скобки: VAR1

Пример:

SET !VAR1 2012

SET !VAR2 New<SP>Year

ADD !VAR2 !VAR1

Итог: New Year 2012

Пример:

SET !VAR1 {{VAR2}}

А так же существует команда сложения ADD, она добавляет значение переменной. Вы также можете вычесть значения путем добавления отрицательное значения переменной. Если по крайней мере одна из переменных содержит не целое число, значения объединяются в виде строчной переменной.

SET !VAR1 49 ‘задаем  значение переменной равное 49

ADD !VAR1 2 ‘прибавляем значению переменной 2, т.е. 49+2=51

Оба значения являются числовыми поэтому результат также числовой:

 SET !VAR1 100

 ADD !VAR1 -20

 => В результате переменная !VAR1 содержит 80.

По крайней мере, одно из значений является строкой поэтому результатом также является строка:

 SET !VAR1 Hello

 ADD !VAR1 <SP>World<SP>

 ADD !VAR1 2011

 => В результате переменная !VAR1 содержит Hello World 2011

Присвоить переменной VAR1 текущее время

SET !VAR1 {{!NOW:hh:nn:ss}}

Администратор

Водитель сайта

Первый почин

Сообщений: 150

Норильск

638 дней назад

0

Самые частые и основные команды

SET !ERRORIGNORE YES

Забиваем на ошибки и идём дальше ))))., после этой команды все ошибки будут в игноре и макрос продолжит работу

SET !ERRORCONTINUE YES

Не даем макросу остановиться, официально применяется, в основном, в паре с командой SET !ERRORIGNORE YES. Неофициально, можно неиспользовать. Мне очень часто хватает команды макроса

SET !ERRORIGNORE YES

, для нормальной работы макроса.

WAIT SECONDS=100

Ставим задержку перед нужной нам командой макроса, измеряется в секундах.

SET !VAR1 EVAL(«var randomNumber=Math.floor(Math.random()*10 + 15); randomNumber;»)
WAIT SECONDS={{!VAR1}}

Команда для рандомной задержки, время измеряется в секундах ( до 25 секунд ).

Случайные команды, пригодятся вам обязательно когда нибудь.

!CLIPBOARD

Переменная !CLIPBOARD содержит в себе буфера обмена. Всё то, что вы скопировали.

SET !ERRORIGNORE NO

Ошибки не игнорируются!!! При получении ошибки на вэбстранице, макрос остановит свою работу.

!NOW

Эта переменная содержит дату и время.

!EXTRACT

Помогает извлекать данные с вэбстраницы с возможностью операций над данными.

!REPLAYSPEED

Назначает быстроту воспроизведения макроса, имеет данные: FASТ-быстро,MEDIUM-средне,SLOW-медленно. (Я всегда ставлю медленно)

REFRESH

Перезагрузить вэбстраницу

Редактировалось: 1 раз (Последний: 31 марта 2014 в 19:05)

Мини хрумер . С постингом в твиттер.

Посетитель

Сообщений: 1

Оффлайн

0

SET !ERRORIGNORE YES
SET !ERRORCONTINUE YES
Не игнорит ошибки,макрос тормозит однозначно!

im trying to run a simple script, loop an imacros over and over but if a link does not exist then move on to the next loop but if the link does exist then just keep running imacros as usual.

This is the script I have made very basic. This is my imacros version

 VERSION BUILD=8601111 RECORDER=FXSET 
 !DATASOURCE check.csv
 TAB T=1
 URL GOTO=http://{{!COL1}}.blogspot.com/
 TAG POS=2 TYPE=A ATTR=HREF:http://{{!COL1}}.blogspot.com/
 'if fail start next loop, if not fail keep running macros
 ADD !EXTRACT {{!COL1}}
 SAVEAS TYPE=EXTRACT FOLDER=c:\iMacros FILE=table.csv

This is my javascript version.

 const iterations = 100; // Number of times to loop
 var macro;
 macro =  "CODE:";
 macro +=  "VERSION BUILD=8300326 RECORDER=FX" + "\n"; 
 macro +=  "SET !ERRORIGNORE YES" + "\n";
 macro +=  "SET !DATASOURCE check.csv" + "\n";
 macro +=  "SET !LOOP 8" + "\n";
 macro +=  "SET !DATASOURCE_COLUMNS 3" + "\n";
 macro +=  "set !var1 1" + "\n";
 macro +=  "add !var1 {{!loop}}" + "\n";
 macro +=  "SET !DATASOURCE_LINE {{!var1}}" + "\n";
 macro +=  "TAB T=1" + "\n";
 macro +=  "URL GOTO=http://{{!COL1}}.blogspot.com/" + "\n";
 macro +=  "SET !ERRORIGNORE NO" + "\n";
 macro +=  "TAG POS=2 TYPE=A ATTR=HREF:http://{{!COL1}}.blogspot.com/" + "\n";
 'if link fail start next loop, if not fail keep running macros
 macro +=  "ADD !EXTRACT {{!COL1}}" + "\n";
 macro +=  "SAVEAS TYPE=EXTRACT FOLDER=c:\iMacros FILE=table.csv" + "\n";
 iimPlay(macro)

Понравилась статья? Поделить с друзьями:
  • Imacros игнорировать ошибки
  • Imacros игнорирование ошибок
  • Ima honda insight ошибка
  • Im151 1 standard ошибки
  • Im cleverest than my brother найдите ошибки