Data Extraction


SUBMITTED BY: rilp44

DATE: Dec. 5, 2015, 1:53 a.m.

FORMAT: Text only

SIZE: 22.9 kB

HITS: 2086

  1. ''"At the Independent Evaluation Unit of the World Bank, we are using iMacros... to streamline our information gathering and research tasks."''
  2. Alex McKenzie, The World Bank
  3. ''"I run ~900 Script against 1500 websites daily. If it wasn't for iMacros I would have to have 3 or 4 people sit around all day and download data."''
  4. Josh Miller, Dataflowservices, Inc.,
  5. __TOC__
  6. == Data Extraction and Web Scraping [[Image:IMacros-icon.png|iMacros Browser]] [[Image:Ie-icon.png|IE Plug-in]] [[Image:Ff-icon.png|Firefox]] [[Image:Cr-icon.png|Chrome]]==
  7. A key activity in web automation is the extraction of data from websites, also known as web scraping or screen scraping. Whether it is price lists, stock information, financial data or any other type of data, iMacros can extract this data for you and either re-use the data or store it in a file or database.
  8. iMacros can write extracted data to standard text files, including the comma separated value (.csv) format, readable by spreadsheet processing packages. Also, iMacros can make use of the powerful scripting interface to save data directly to databases.
  9. === The Extract command ===
  10. Data extraction is specified by an [[TAG#The_EXTRACT_Parameter|EXTRACT]] parameter in the [[TAG|TAG]] command. This parameter ''replaces'' the usual CONTENT parameter. Please see the updated Demo-Extract for some examples of this, including the following:
  11. TAG POS=1 TYPE=SPAN ATTR=CLASS:bdytxt&&TXT:* EXTRACT=HTM
  12. This means that the syntax of the command is now the same as for the TAG command, with the type of extraction specified by the additional EXTRACT parameter.
  13. == Creation of Extraction Tags ==
  14. === Extraction Wizard [[Image:IMacros-icon.png|iMacros Browser]] [[Image:Ie-icon.png|IE Plug-in]]===
  15. [[Image:TextExtract.png|thumb|350px|Text Extraction Wizard]]
  16. The Extraction Wizard can be used to automatically generate and test extractions.
  17. To define an EXTRACT command proceed as follows:
  18. * Whilst in record mode, open the Text Extraction Wizard ("Text" button on the Rec tab).
  19. * In the browser window or frame select the text that you want to extract.
  20. * Choose what type of extraction you want to perform on that element, like TXT, HTM, HREF, ALT, TXTALL, or TITLE. Not all types are available for all elements.
  21. * The extracted information will be displayed in the wizard. iMacros also creates a suggestion for the tag command attribute and position.
  22. * If the result is #EANF# (Extraction Anchor Not Found) you will need to alter the extraction anchor in order to successfully extract the data.
  23. * If you are satisfied with the result click "Add Command" to add a TAG command with the EXTRACT statement to the macro.
  24. Table extract commands can be easily produced and checked using the Text Extract Wizard. If the element chosen is a table, the table data is properly formatted and displayed in the wizard.
  25. [[Image:IMacros-icon.png|iMacros Browser]]'''Note:''' The extraction wizard is '''only available in the iMacros Browser and iMacros for Internet Explorer''' But the generated commands can be used in all iMacros versions.
  26. === Extraction from Framed Websites ===
  27. If the information you want to extract is inside a framed web site you need to have a FRAME command to mark the frame as active for extraction.
  28. When recording a TAG command the FRAME command will automatically be generated.
  29. URL GOTO=http://demo.imacros.net/Automate/Frames
  30. FRAME F=5
  31. TAG POS=1 TYPE=P ATTR=TXT:<SP>Frame5
  32. Within the Extraction Wizard, when selecting the data to be extracted the FRAME command will automatically be generated.
  33. URL GOTO=http://demo.imacros.net/Automate/Frames
  34. FRAME F=3
  35. TAG POS=1 TYPE=P ATTR=TXT:* EXTRACT=TXT
  36. === Manual Creation [[Image:IMacros-icon.png|iMacros Browser]] [[Image:Ie-icon.png|IE Plug-in]] [[Image:Ff-icon.png|Firefox]] [[Image:Cr-icon.png|Chrome]]===
  37. In order to manually create an extraction tag it is necessary to first record a TAG command. In record mode click on the data to be extracted. After stopping the macro recording, open the macro for editing and '''replace''' the CONTENT= attribute with the [[TAG#The_EXTRACT_Parameter|EXTRACT=TXT]] parameter (or just simply add the EXTRACT parameter to the end of command if the CONTENT parameter does not exist). If you need to extract other information than text you can use the TXTALL, HTM, HREF, TITLE, ALT or CHECKED attribute instead of TXT.
  38. TAG POS=1 TYPE=TD ATTR=CLASS:NewLatestResultsLotto&&TXT:* EXTRACT=TXT
  39. Starting with iMacros 10.2, you can extract any attribute. If you want to know which attributes are available, record the TAG command in ''[http://wiki.imacros.net/First_Steps#Expert Expert Mode]''.
  40. '''Example:'''
  41. Normally, the tooltips are specified by the TITLE attribute of an element. You can extract the tooltip content with iMacros:
  42. [[Image:7.1.png|left|400px]]
  43. The qTip tooltip plugin for the jQuery JavaScript framework uses not the title attribute but a custom attribute named "data-qtip":
  44. [[Image:7.2.png|left|580px]]
  45. ComputerName=* is the initial immutable part of the tooltip content and is used to specify which tooltip should be extracted. Recording in ''[http://wiki.imacros.net/First_Steps#Expert Expert Mode]'' will create a TAG command that consists of all attributes of the clicked HTML element.
  46. === Extract Complete Website [[Image:IMacros-icon.png|iMacros Browser]] [[Image:Ie-icon.png|IE Plug-in]] [[Image:Ff-icon.png|Firefox]] [[Image:Cr-icon.png|Chrome]]===
  47. To extract a complete web page (or the complete header or body) you need to manually insert the appropriate TAG line. Please see the examples:
  48. URL GOTO=http://www.imacros.net
  49. 'Complete Page
  50. TAG POS=1 TYPE=HTML ATTR=* EXTRACT=HTM
  51. 'Complete Page TEXT only
  52. TAG POS=1 TYPE=HTML ATTR=* EXTRACT=TXT
  53. 'Page header only
  54. TAG POS=1 TYPE=HEAD ATTR=* EXTRACT=HTM
  55. 'Page body
  56. TAG POS=1 TYPE=BODY ATTR=* EXTRACT=HTM
  57. Alternatively you can use the [[SAVEAS]] command to save the complete web page.
  58. For an example using the [[SEARCH]] command, please see the following forum post: [http://forum.imacros.net/viewtopic.php?f=7&t=11200 Most Efficient Way To Extract Source Code]
  59. === Extract Table [[Image:IMacros-icon.png|iMacros Browser]] [[Image:Ie-icon.png|IE Plug-in]] [[Image:Ff-icon.png|Firefox]]===
  60. [[File:ExtractionWizard.png|left|320px|thumb|Table extraction with the Text Extraction Wizard]]
  61. Use TAG TYPE=TABLE ... to extract the content of a complete table with one command. Example: [[Demo-Extract-Table]].
  62. This method works well with well formatted tables. For more tricky table extractions you always have the option to extract them cell by cell as shown in the [[!ENDOFPAGE]] example.
  63. Table cells in the extracted data are separated by the string #NEXT# and table rows are delimited by the string #NEWLINE#. These tags are automatically translated into commas and newlines when you use the "SAVEAS TYPE=EXTRACT" command, but the delimiters are retained when returning the data to a script via a call to [[iimGetExtract]].
  64. If the table you are attempting to extract also contains nested tables, then the inner table data will also be separated by commas and new lines (in CSV format, via SAVEAS), or #NEXT# and #NEWLINE# (via [[iimGetExtract]]).
  65. You can use the Text Extraction Wizard to see the resulting extracted table, but in this case, for visual simplicity, the inner tables are shown as plain text, without the delimiters.
  66. === Extract Page Title [[Image:IMacros-icon.png|iMacros Browser]] [[Image:Ie-icon.png|IE Plug-in]] [[Image:Ff-icon.png|Firefox]]===
  67. To extract a title of a website you need to manually insert the appropriate TAG line with '''TYPE=TITLE'''. This TAG command finds the page's title element. Please see the example:
  68. URL GOTO=http://www.imacros.net/
  69. TAG POS=1 TYPE=TITLE ATTR=* EXTRACT=TXT
  70. === Extract Page URL [[Image:IMacros-icon.png|iMacros Browser]] [[Image:Ie-icon.png|IE Plug-in]] [[Image:Ff-icon.png|Firefox]]===
  71. To extract the URL of a website as shown in the browser address bar please use the built-in [[!URLCURRENT]] variable and store this value in [[!EXTRACT]] with the [[set|SET]] or [[ADD]] command.
  72. ADD !EXTRACT <nowiki>{{!URLCURRENT}}</nowiki>
  73. === Test Popup ===
  74. When manually running a macro with an extraction TAG, by default the extraction will be displayed on the screen. This facility can be switched off using the following command:
  75. SET !EXTRACT_TEST_POPUP NO
  76. == Handling Extraction Results ==
  77. If in one macro several EXTRACT commands appear then the results are separated by the string [EXTRACT].
  78. === SAVEAS ===
  79. You can save extracted data directly to a [[csv|CSV]] file by adding a "SAVEAS TYPE=EXTRACT" command manually to the macro. All items that were extracted before the [[SAVEAS]] command are saved to the specified file in one row like
  80. "item1", "item2", "item 3", ...
  81. As you can see the [EXTRACT] tags, which are inserted to distinguish results from different EXTRACT commands, are substituted by commas. If in the Options dialog you have checked "Use regional settings in CSV files", the "comma" between each extraction is going to be your system list separator (a semi-colon ";" for instance) instead of ",".
  82. The [[SAVEAS]] command erases the content of the !EXTRACT variable afterward. With the next start of the macro or the next round of a loop a new line is added to the file.
  83. ==== Saving arbitrary values ====
  84. In addition to extracting data from web pages, you can also save any arbitrary value to your output file by adding it to the extraction buffer with the following syntax:
  85. ADD !EXTRACT <value>
  86. Where <value> is replaced with the actual value you want to save (can also be an [[EVAL]] expression). For example, the following will add a time stamp column to the output:
  87. ADD !EXTRACT <nowiki>{{!NOW:yyyy/mm/dd_hhnn}}</nowiki>
  88. Each time you add something to !EXTRACT either by using the [[ADD]] command or as part of a TAG...EXTRACT command, it will save that value as a separate column when using SAVEAS TYPE=EXTRACT.
  89. === Extraction & the Scripting Interface ===
  90. (Related example scripts: Extract-and-fill.vbs, Extract-2-file.vbs, Get-Exchange-Rate.vbs)
  91. All extracted data can be sent to your code via the Scripting Interface. This gives you all the power of any programming language you choose to process the extracted information further or simply save it to a file.
  92. Use the [[iimGetLastExtract]] command to return the extracted information from the macro.
  93. The extracted text is returned as a string. Extracted information resulting from different extractions are separated by [EXTRACT], e.g.
  94. Text to be extracted[EXTRACT]
  95. Salary: 33,000.00 per year[EXTRACT]...
  96. Remember: Using the "SAVEAS TYPE=EXTRACT" command will reset the contents of the !EXTRACT variable. Thus, using this command in a macro whose extraction result you wish to obtain via the Scripting Interface will result in an empty string in your application!
  97. If you extract a complete table the data from different columns is separated by #NEXT# and each table row ends with #NEWLINE#. You can easily use the separation tags to split the complete dataset. In Visual Basic Script this would, for example, look something like:
  98. s = Replace(s, "#NEWLINE#", """" + vbCrLf + """")
  99. s = Replace(s, "#NEXT#", """"+ "," + """")
  100. Related forum post: [http://forum.imacros.net/viewtopic.php?f=7&t=12375&p=36478#p36478 Missing #NEXT# delimiters in .csv from web extraction]
  101. ==== Example 1 - Transfer extracted values to calling program ====
  102. Use [[iimGetLastExtract]] to retrieve the values.
  103. iplay = iim1.iimPlay("wsh-extract-rate")
  104. If iplay = 1 Then
  105. s = "One US$ costs " + iim1.iimGetLastExtract(1) + " EURO or " + iim1.iimGetLastExtract(2) + " British Pounds (GBP)"
  106. else
  107. s = "The following error occurred: " + iim1.iimGetLastError()
  108. End If
  109. === Unsuccessful Extraction ===
  110. If the extraction was unsuccessful, i.e. the extraction anchor could not be found on the page, the !EXTRACT variable holds the string #EANF# (Extraction Anchor Not Found). ''However, the return value that informs you whether the execution of a macro was successful is still positive (iimPlay = 1)''. The reason for this behavior is that a macro can have many TAG...EXTRACT commands and often only one or a few of them do not find the extraction anchor. If you want to check if a particular EXTRACT command was successful you just need to check if #EANF# is present in the returned string. Often this can be very useful, for example if you use EXTRACT to check if a keyword is present on a page. A returned string containing #EANF# indicates that the keyword is not found. For comparison, if a standard [[TAG]] command cannot locate the defined element then iMacros returns an error.
  111. == Image Extraction ==
  112. The Image Extraction Wizard helps you the create the right commands TAG... CONTENT=EVENT:[[SAVEITEM]] for image web scraping. Please see the [[Browser_Automation#Save_Website_Elements|Save Web Page Elements]] chapter for more details.
  113. == Extraction of Dialog Text ==
  114. [[Image:Extract-dialog-text.png]]<br>To get the text of a dialog use
  115. SET !EXTRACTDIALOG YES
  116. in the macro at any position before dialog appears. Now the content of a dialog is added to the extracted text, i.e. to the [[!EXTRACT]] variable.
  117. '''Example:'''
  118. URL GOTO=http://demo.imacros.net/Automate/Dialogs
  119. SET !EXTRACTDIALOG YES
  120. ONDIALOG POS=1 BUTTON=OK CONTENT=
  121. TAG POS=1 TYPE=INPUT:BUTTON FORM=NAME:NoFormName ATTR=VALUE:Popup<SP>1
  122. WAIT SECONDS=3
  123. PROMPT <nowiki>{{!EXTRACT}}</nowiki>
  124. The [[PROMPT]] command in this example is simply used to show the extracted values. The WAIT statement is not directly required, but there has to be a 1-2 seconds delay between the time you trigger the dialog and ''the first time you use the extracted dialog text''. The reason for this is that there is a small delay between the time the TAG command triggers the dialog (e. g. by clicking on a link) and the time the dialog actually appears. iMacros has no way of knowing beforehand that a certain link will trigger a dialog. So it has to "catch" the dialog once it appears and then handle it. Typically this whole process is fast and takes less than a second, but until it is complete the [[!EXTRACT]] variable is not filled with the text from the dialog.
  125. See also [[!EXTRACTDIALOG]].
  126. == Extracting From SELECT Elements ==
  127. In HTML code drop down lists are generated by a SELECT tag.
  128. With a simple EXTRACT=TXT, the currently active value is extracted:
  129. TAG POS=1 TYPE=SELECT ATTR=TXT:*&&NAME:quantity&&VALUE:* EXTRACT=TXT
  130. In order to extract all options in a drop down list use
  131. TAG POS=1 TYPE=SELECT ATTR=TXT:*&&NAME:quantity&&VALUE:* EXTRACT=TXTALL
  132. [[!EXTRACT]] will contain the complete list of entries, separated by the keyword [OPTION]
  133. Related forum posts: [http://forum.imacros.net/viewtopic.php?f=13&t=12982 How to extract value from option tag instead of text]
  134. == Extraction and the PRE Tag ==
  135. Some web pages make use of a <nowiki><PRE ...></nowiki> tag in their HTML code. It marks the enclosed text as preformatted -- all the spaces and carriage returns are rendered exactly as you type them. The information enclosed in a <nowiki><PRE></nowiki> tag is extracted correctly (including the formatting!) by iMacros. Thus, if you transfer the extracted data via the Scripting Interface all formatting information is retained unchanged. The formatting is only changed on two occasions: line breaks are removed when displaying the result in the test dialog box and when saving the result using the SAVEAS command. This is necessary to ensure proper formatting of the CSV formatted text file because in the CSV format a line break would start a new line.
  136. == Extract with relative Positioning ==
  137. (Related example macro: [[Demo-ExtractRelative]] )
  138. Note: For changes in the upcoming [[Upgrading_to_Version_7|iMacros V7]] please see [[V7_Relative_positioning]]. In a nutshell, the principle stays the same, but the position is now relative to the end (close tag) of the anchor element, so iMacros V7 and iMacros for Firefox extract macros are now compatible.
  139. ----
  140. [[File:Extract gold price.png|thumb|center|550px|Extract the current gold price (sell/buy) given the item number. We use relative extraction to get the prices in the line with the correct item number.]]
  141. When extracting data from a complex website the extraction can be made easier if you can tell iMacros to start the search for the extraction anchor after a specific point on the page (as opposed to start from the top, which is the default).
  142. E.g., assume you want to extract data from a specific cell in a table, in this case the size of the land in the second table.
  143. [[Image:Result1.gif|frame|Table 1 - Relative Extraction]][[Image:Result2.gif|frame|Table 2 - Relative Extraction]]
  144. Without relative positioning you would have to count the cell from the top of the page including cells from other tables that come before the land table. Although the extraction wizard can do this for you, you run into problems as soon as the number of rows in a table are not constant as they are in the above example. The Transfer table of result 1 has four rows, that of result 2 has five rows. Thus, an absolute position parameter like so
  145. <nowiki>TAG POS=1 TYPE=TD ATTR=CLASS:code&&TXT:* EXTRACT=TXT</nowiki>
  146. will potentially result in the extraction of an unwanted result.
  147. '''With relative positioning you tell iMacros to search for the extraction anchor located after the position that is indicated by a TAG command immediately before your TAG...EXTRACT command.''' In our case we click on the table title "Land" before starting the extraction wizard to create a TAG command. Note that this TAG command does not click on any link, rather it only marks an element to indicate a position for the following TAG command. Relative positions are indicated with an R before the position number.
  148. TAG POS=1 TYPE=B ATTR=TXT:Land
  149. <nowiki>TAG POS=R1 TYPE=TXT ATTR=CLASS:code&&TXT:* EXTRACT=TXT</nowiki>
  150. * If you want to use a button or a link as reference, you should tag it with TAG ... EXTRACT=TXT, to avoid following the link or "pushing" the button. In that case, do not forget to use SET !EXTRACT NULL, to clear the extract variable '''before''' the real extract.
  151. ===How to limit the extraction search range===
  152. Use [[!ENDOFPAGE]] to limit the extraction to a range '''above''' a certain trigger word or image.
  153. [[Image:Amazon_extract.png‎|thumb|center|350px|Extracting data from Amazon.com with Relative Positioning. In this example we use the word "Price" to find the book price. This creates very stable web-scraping macros.]]
  154. '''Backwards relative positions:'''
  155. Since iMacros V6.20 you can also indicate backward positions (= to the left and/or top of an selected element). This '''negative''' relative extractions supports up to 10 backwards steps (POS=R-10).
  156. 'Negative positioning => move to the LEFT and/or TOP of the anchor
  157. TAG POS=1 TYPE=TD ATTR=TXT:31023G20080822
  158. TAG POS=R-1 TYPE=INPUT:CHECKBOX FORM=NAME:DataDownloadActionForm ATTR=NAME:* CONTENT=YES
  159. [[Image:Checkbox.with.negative.position.png|thumb|center|350px|Negative (backward) Positioning. The task is to select the checkbox to the left of a given order-ID. Since the select box itself has no name, we use the ID in the second column to find the checkbox.]]
  160. ===How to skip a missing value===
  161. If you use relative extraction and a certain data record (e. g. a phone number) is missing on a page, then the macro would normally stop with a TAG error as the TAG for the anchor fails. But that is not what you want during an extraction: You simply want the macro to continue and extract all other values that exist. => Solution: '''Add ''SET !ERRORIGNORE YES'''''.
  162. Note that when the anchor TAG immediately before a '''relative''' extraction fails, then the extraction itself also fails (= returns #eanf#). This is by design to make sure that iMacros extracts only the intended value (if the extraction anchor exists) or no value ("#eanf#") if the extraction anchor is not found.
  163. Example:
  164. URL GOTO=http://demo.imacros.net/Automate/Extract2
  165. SET !ERRORIGNORE YES
  166. 'Correct: TAG POS=1 TYPE=DIV ATTR=TXT:MyTable
  167. TAG POS=1 TYPE=DIV ATTR=TXT:MyTableOTHERNAME
  168. TAG POS=R3 TYPE=TD ATTR=TXT:* EXTRACT=TXT
  169. OTHERNAME was added to the ''TXT:MyTable'' attribute to trigger the extraction anchor failure for demo purposes.
  170. ===Related forum posts===
  171. * '''[http://forum.imacros.net/viewtopic.php?t=2219 Video Tutorial Relative Extraction]'''
  172. * [http://forum.imacros.net/viewtopic.php?t=3615 Three fundamental techniques of extracting a table's data]
  173. * [http://forum.imacros.net/viewtopic.php?f=13&t=6324 Extract Number of Google Search Results]
  174. * [http://forum.imacros.net/viewtopic.php?t=287 More Robust Extraction Tags]
  175. * [http://forum.imacros.net/viewtopic.php?t=153 Extract a table line by line]
  176. * [http://forum.imacros.net/viewtopic.php?f=7&t=5661&p=15799#p15799 Extracting flight prices from Expedia]
  177. * [http://forum.imacros.net/viewtopic.php?f=2&t=5793 Extract and parse HTML if elements are separated by <BR> only]
  178. * [http://forum.imacros.net/viewtopic.php?f=11&t=5881&p=16530#p16530 Nested elements: When does the search start?]
  179. * [http://forum.imacros.net/viewtopic.php?f=11&t=5474 Extracting data from Amazon.com]
  180. * [http://forum.imacros.net/viewtopic.php?f=7&t=5987 Finding anchors]
  181. * [http://forum.imacros.net/viewtopic.php?f=15&t=6078 How to mark and remove SPAM from web helpdesk]
  182. * [http://forum.imacros.net/viewtopic.php?f=7&t=6223 How to extract a certain word in paragraph?]
  183. * [http://forum.imacros.net/viewtopic.php?f=11&t=6774&p=19323#p19323 How to click on the last element on a page?]
  184. * [http://forum.imacros.net/viewtopic.php?f=13&t=15565 Extracting nested tables]
  185. * [http://forum.imacros.net/viewtopic.php?f=7&t=10390&start=15#p33539 Yellow Pages example]
  186. ==Asian Language Support==
  187. iMacros runs on all language version of Windows, including the so-called "double-byte" languages like Chinese, Japanese or Korean.
  188. '''Asian Languages Text Extraction:'''
  189. iMacros and the Scripting Interface include full Unicode support, so you can extract Asian language characters (e.g. Japanese) even on Western Windows versions (e.g. English).
  190. For more details please see these forum posts:
  191. * '''[http://forum.imacros.net/viewtopic.php?t=2687 Solution if extraction fails on certain character encodings]'''
  192. * [http://forum.imacros.net/viewtopic.php?t=2783 What is Unicode, ASCII, and ANSI?]
  193. == See Also ==
  194. [[!EXTRACTDIALOG]]

comments powered by Disqus