Advertisement
Guest User

Untitled

a guest
Dec 11th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         RecordingAdcogov
  3. // @namespace    http://tampermonkey.net/
  4. // @version      1.0
  5. // @description  Scraper for http://recording.adcogov.org
  6. // @author       IB
  7. // @match        http://recording.adcogov.org/LandmarkWeb/search/index?theme=.blue&section=*
  8. // @grant        none
  9. // @require      https://cdnjs.cloudflare.com/ajax/libs/notify/0.4.2/notify.min.js
  10. // @require      https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js
  11. // @require      https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js
  12. // @require      https://cdnjs.cloudflare.com/ajax/libs/jszip-utils/0.0.2/jszip-utils.min.js
  13. // ==/UserScript==
  14.  
  15. debugger;
  16. var App = (function () {
  17.     var data = [];
  18.     var lastRecordInstrumentNumber;
  19.     var count = 0;
  20.  
  21.     return {
  22.         waitFor: function (condition, log, callback, parameters) {
  23.             console.log('Entering in waitfor');
  24.             var checkExist = setInterval(function () {
  25.                 if (condition()) {
  26.                     console.log(log);
  27.                     clearInterval(checkExist);
  28.                     callback(parameters);
  29.                 }
  30.             }, 100); // check every 100ms
  31.         },
  32.  
  33.         start: function () {
  34.             var that = this;
  35.             that.waitFor(function () {
  36.                     return $('#resultsTable > tbody').children().length;
  37.                 },
  38.                 'Results table was filled',
  39.                 this.scrapeResultPage, that);
  40.         },
  41.         getRowsElementsForClick: function () {
  42.             return $("tr[role='row']([class='result odd'],[class='even result'])");
  43.         },
  44.  
  45.         scrapeResultPage: function (obj) {
  46.             let rows = obj.getRowsElementsForClick();
  47.             if (confirm('Do you want to scrape pages + pdfs?'))
  48.                 if (rows.length > 1) {
  49.                     rows[2].children[3].click();
  50.                     obj.waitFor(function () {
  51.                             return $("label[for='Instrument # ']").length;
  52.                         },
  53.                         'Label was loaded',
  54.                         obj.scrapeSingleRecord, obj
  55.                     );
  56.                 }
  57.                 else
  58.                     alert('Result table is empty')
  59.         },
  60.  
  61.         scrapeSingleRecord: function (obj) {
  62.             count++;
  63.             let item = {};
  64.             item['instrument'] = obj.getTextOfLabelNode('Instrument # ');
  65.             $.notify('Scraping: ' + item['instrument'], 'success', {showDuration: 10000, position: 'center'});
  66.             lastRecordInstrumentNumber = item['instrument'];
  67.             item['bookPage'] = obj.getTextOfLabelNode('Book/Page ');
  68.             item['recordDate'] = obj.getTextOfLabelNode('Record Date ');
  69.             item['bookType'] = obj.getTextOfLabelNode('Book Type ');
  70.             item['docType'] = obj.getTextOfLabelNode('Doc Type ');
  71.             item['numberOfPages'] = obj.getTextOfLabelNode('Number of Pages ');
  72.             item['tdOfPages'] = obj.getTextOfLabelNode('TD # of Pages ');
  73.             item['grantor'] = obj.getTextOfLabelNode('Grantor ');
  74.             item['grantee'] = obj.getTextOfLabelNode('Grantee ');
  75.             item['salesPrice'] = obj.getTextOfLabelNode('Sales Price ');
  76.             item['docLinks'] = obj.getTextOfLabelNode('Doc Links ');
  77.             item['legal'] = obj.getTextOfLabelNode('Legal ');
  78.             item['docLegals'] = obj.getTextOfLabelNode('Doc. Legals ');
  79.             item['pdfUrl'] = obj.getPDFUrl();
  80.             data.push(item);
  81.             let nextNavigator = $('#directNavNext');
  82.             if ($(nextNavigator).is(":visible")) {
  83.                 $('#directNavNext').click();
  84.             }
  85.             else {
  86.                 $.notify('Saving csv . . . ', 'success', {showDuration: 10000, position: 'center'});
  87.                 obj.toCsv(data);
  88.                 $.notify('Downloading pdfs . . . Please, wait.', 'success', {showDuration: 10000, position: 'center'});
  89.                 obj.savePdfs(data);
  90.             }
  91.             // fetch next record
  92.             obj.waitFor(function () {
  93.                     return obj.getTextOfLabelNode('Instrument # ') !== lastRecordInstrumentNumber;
  94.                 },
  95.                 'Fetching the next record...', obj.scrapeSingleRecord, obj);
  96.         },
  97.  
  98.         getTextOfLabelNode: function (forLabel) {
  99.             return $($(`label[for='${forLabel}']`).parent().parent().children()[1]).text().trim();
  100.         },
  101.  
  102.         savePdfs: function (array) {
  103.             let downloaded = 0;
  104.             let zip = new JSZip();
  105.             let download = function (item) {
  106.                 return new Promise(function (resolve) {
  107.                     try {
  108.                         JSZipUtils.getBinaryContent(item['pdfUrl'], function (err, data) {
  109.                             if (err) {
  110.                                 throw err; // or handle the error
  111.                             }
  112.                             zip.file(item['instrument'] + '.pdf', data, {
  113.                                 binary: true
  114.                             });
  115.                             downloaded++;
  116.                             $.notify('Downloaded pdf: ' + item['instrument'] + '.pdf | Downloaded ' + downloaded + '/' + array.length,
  117.                                 'success', {showDuration: 10000, position: 'center'});
  118.                             resolve();
  119.                         });
  120.                     }
  121.                     catch {
  122.                         console.log('Exception in pdf downloading ')
  123.                     }
  124.                 });
  125.             };
  126.  
  127.             Promise.all(array.map(function (item) {
  128.                 return download(item);
  129.             }))
  130.                 .then(function () {
  131.                     console.log(zip);
  132.                     zip.generateAsync({
  133.                         type: "blob"
  134.                     })
  135.                         .then(function (content) {
  136.                             saveAs(content, 'documents.zip');
  137.                         });
  138.                 });
  139.  
  140.  
  141.         },
  142.  
  143.         toCsv: function (array) {
  144.             var headers = [];
  145.             for (var i = 0; i < array.length; i++) {
  146.                 var objHeaders = [];
  147.                 for (var key in array[i]) {
  148.                     if (headers.indexOf(key) == -1) {
  149.                         headers.push(key);
  150.                     }
  151.                 }
  152.             }
  153.             for (var i = 0; i < array.length; i++) {
  154.                 for (var j = 0; j < headers.length; j++) {
  155.                     if (!(headers[j] in array[i])) {
  156.                         array[i][headers[j]] = '';
  157.                     }
  158.                 }
  159.             }
  160.  
  161.             var keys = Object.keys(array[0]);
  162.  
  163.             var result = '"' + keys.join('","') + '"' + '\n';
  164.  
  165.             array.forEach(function (obj) {
  166.                 keys.forEach(function (k, ix) {
  167.                     if (ix == 0) {
  168.                         result += '"' + obj[k].trim() + '"';
  169.                     } else {
  170.                         result += ',"' + obj[k].trim() + '"';
  171.                     }
  172.                 });
  173.                 result += "\n";
  174.             });
  175.  
  176.             var a = document.createElement('a');
  177.             a.href = 'data:attachment/csv,' + encodeURIComponent(result);
  178.             a.target = '_blank';
  179.             a.download = 'result.csv';
  180.             document.body.appendChild(a);
  181.             a.click();
  182.         },
  183.  
  184.         getPDFUrl: function () {
  185.             let regexp = /\(".*"\)/g;
  186.             let functionBody = $._data($("#DocumentViewButtonAll")[0])
  187.                 ['events']['click'][0].handler.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1];
  188.             let pdfId = functionBody.match(regexp)[0].replace('(', '').replace(')', '').replace('"', '').replace('"', '');
  189.             return 'http://recording.adcogov.org/LandmarkWeb//Document/GetDocumentForPrint/?request=' + encodeURIComponent(pdfId);
  190.         },
  191.  
  192.  
  193.     };
  194. }());
  195.  
  196. App.start();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement