asdfadsfycvx
60 | # 61 | # 62 | if page.evaluate(-> 63 | typeof PhantomJSPrinting is "object" 64 | ) 65 | paperSize = page.paperSize 66 | paperSize.header.height = page.evaluate(-> 67 | PhantomJSPrinting.header.height 68 | ) 69 | paperSize.header.contents = phantom.callback((pageNum, numPages) -> 70 | page.evaluate ((pageNum, numPages) -> 71 | PhantomJSPrinting.header.contents pageNum, numPages 72 | ), pageNum, numPages 73 | ) 74 | paperSize.footer.height = page.evaluate(-> 75 | PhantomJSPrinting.footer.height 76 | ) 77 | paperSize.footer.contents = phantom.callback((pageNum, numPages) -> 78 | page.evaluate ((pageNum, numPages) -> 79 | PhantomJSPrinting.footer.contents pageNum, numPages 80 | ), pageNum, numPages 81 | ) 82 | page.paperSize = paperSize 83 | console.log page.paperSize.header.height 84 | console.log page.paperSize.footer.height 85 | window.setTimeout (-> 86 | page.render output 87 | phantom.exit() 88 | ), 200 89 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/printheaderfooter.js: -------------------------------------------------------------------------------- 1 | var page = require('webpage').create(), 2 | system = require('system'); 3 | 4 | function someCallback(pageNum, numPages) { 5 | return "asdfadsfycvx
63 | 64 | */ 65 | if (page.evaluate(function(){return typeof PhantomJSPrinting == "object";})) { 66 | paperSize = page.paperSize; 67 | paperSize.header.height = page.evaluate(function() { 68 | return PhantomJSPrinting.header.height; 69 | }); 70 | paperSize.header.contents = phantom.callback(function(pageNum, numPages) { 71 | return page.evaluate(function(pageNum, numPages){return PhantomJSPrinting.header.contents(pageNum, numPages);}, pageNum, numPages); 72 | }); 73 | paperSize.footer.height = page.evaluate(function() { 74 | return PhantomJSPrinting.footer.height; 75 | }); 76 | paperSize.footer.contents = phantom.callback(function(pageNum, numPages) { 77 | return page.evaluate(function(pageNum, numPages){return PhantomJSPrinting.footer.contents(pageNum, numPages);}, pageNum, numPages); 78 | }); 79 | page.paperSize = paperSize; 80 | console.log(page.paperSize.header.height); 81 | console.log(page.paperSize.footer.height); 82 | } 83 | window.setTimeout(function () { 84 | page.render(output); 85 | phantom.exit(); 86 | }, 200); 87 | } 88 | }); 89 | } 90 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/printmargins.coffee: -------------------------------------------------------------------------------- 1 | page = require("webpage").create() 2 | system = require("system") 3 | if system.args.length < 7 4 | console.log "Usage: printmargins.js URL filename LEFT TOP RIGHT BOTTOM" 5 | console.log " margin examples: \"1cm\", \"10px\", \"7mm\", \"5in\"" 6 | phantom.exit 1 7 | else 8 | address = system.args[1] 9 | output = system.args[2] 10 | marginLeft = system.args[3] 11 | marginTop = system.args[4] 12 | marginRight = system.args[5] 13 | marginBottom = system.args[6] 14 | page.viewportSize = 15 | width: 600 16 | height: 600 17 | 18 | page.paperSize = 19 | format: "A4" 20 | margin: 21 | left: marginLeft 22 | top: marginTop 23 | right: marginRight 24 | bottom: marginBottom 25 | 26 | page.open address, (status) -> 27 | if status isnt "success" 28 | console.log "Unable to load the address!" 29 | else 30 | window.setTimeout (-> 31 | page.render output 32 | phantom.exit() 33 | ), 200 34 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/printmargins.js: -------------------------------------------------------------------------------- 1 | var page = require('webpage').create(), 2 | system = require('system'); 3 | 4 | if (system.args.length < 7) { 5 | console.log('Usage: printmargins.js URL filename LEFT TOP RIGHT BOTTOM'); 6 | console.log(' margin examples: "1cm", "10px", "7mm", "5in"'); 7 | phantom.exit(1); 8 | } else { 9 | var address = system.args[1]; 10 | var output = system.args[2]; 11 | var marginLeft = system.args[3]; 12 | var marginTop = system.args[4]; 13 | var marginRight = system.args[5]; 14 | var marginBottom = system.args[6]; 15 | page.viewportSize = { width: 600, height: 600 }; 16 | page.paperSize = { 17 | format: 'A4', 18 | margin: { 19 | left: marginLeft, 20 | top: marginTop, 21 | right: marginRight, 22 | bottom: marginBottom 23 | } 24 | }; 25 | page.open(address, function (status) { 26 | if (status !== 'success') { 27 | console.log('Unable to load the address!'); 28 | } else { 29 | window.setTimeout(function () { 30 | page.render(output); 31 | phantom.exit(); 32 | }, 200); 33 | } 34 | }); 35 | } 36 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/rasterize.coffee: -------------------------------------------------------------------------------- 1 | page = require('webpage').create() 2 | system = require 'system' 3 | 4 | if system.args.length < 3 or system.args.length > 4 5 | console.log 'Usage: rasterize.coffee URL filename [paperwidth*paperheight|paperformat]' 6 | console.log ' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"' 7 | phantom.exit 1 8 | else 9 | address = system.args[1] 10 | output = system.args[2] 11 | page.viewportSize = { width: 600, height: 600 } 12 | if system.args.length is 4 and system.args[2].substr(-4) is ".pdf" 13 | size = system.args[3].split '*' 14 | if size.length is 2 15 | page.paperSize = { width: size[0], height: size[1], border: '0px' } 16 | else 17 | page.paperSize = { format: system.args[3], orientation: 'portrait', border: '1cm' } 18 | page.open address, (status) -> 19 | if status isnt 'success' 20 | console.log 'Unable to load the address!' 21 | phantom.exit() 22 | else 23 | window.setTimeout (-> page.render output; phantom.exit()), 200 24 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/rasterize.js: -------------------------------------------------------------------------------- 1 | var page = require('webpage').create(), 2 | system = require('system'), 3 | address, output, size; 4 | 5 | if (system.args.length < 3 || system.args.length > 5) { 6 | console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]'); 7 | console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"'); 8 | phantom.exit(1); 9 | } else { 10 | address = system.args[1]; 11 | output = system.args[2]; 12 | page.viewportSize = { width: 600, height: 600 }; 13 | if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") { 14 | size = system.args[3].split('*'); 15 | page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' } 16 | : { format: system.args[3], orientation: 'portrait', margin: '1cm' }; 17 | } 18 | if (system.args.length > 4) { 19 | page.zoomFactor = system.args[4]; 20 | } 21 | page.open(address, function (status) { 22 | if (status !== 'success') { 23 | console.log('Unable to load the address!'); 24 | phantom.exit(); 25 | } else { 26 | window.setTimeout(function () { 27 | page.render(output); 28 | phantom.exit(); 29 | }, 200); 30 | } 31 | }); 32 | } 33 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/render_multi_url.coffee: -------------------------------------------------------------------------------- 1 | # Render Multiple URLs to file 2 | 3 | system = require("system") 4 | 5 | # Render given urls 6 | # @param array of URLs to render 7 | # @param callbackPerUrl Function called after finishing each URL, including the last URL 8 | # @param callbackFinal Function called after finishing everything 9 | RenderUrlsToFile = (urls, callbackPerUrl, callbackFinal) -> 10 | urlIndex = 0 # only for easy file naming 11 | webpage = require("webpage") 12 | page = null 13 | getFilename = -> 14 | "rendermulti-" + urlIndex + ".png" 15 | 16 | next = (status, url, file) -> 17 | page.close() 18 | callbackPerUrl status, url, file 19 | retrieve() 20 | 21 | retrieve = -> 22 | if urls.length > 0 23 | url = urls.shift() 24 | urlIndex++ 25 | page = webpage.create() 26 | page.viewportSize = 27 | width: 800 28 | height: 600 29 | 30 | page.settings.userAgent = "Phantom.js bot" 31 | page.open "http://" + url, (status) -> 32 | file = getFilename() 33 | if status is "success" 34 | window.setTimeout (-> 35 | page.render file 36 | next status, url, file 37 | ), 200 38 | else 39 | next status, url, file 40 | 41 | else 42 | callbackFinal() 43 | 44 | retrieve() 45 | arrayOfUrls = null 46 | if system.args.length > 1 47 | arrayOfUrls = Array::slice.call(system.args, 1) 48 | else 49 | # Default (no args passed) 50 | console.log "Usage: phantomjs render_multi_url.js [domain.name1, domain.name2, ...]" 51 | arrayOfUrls = ["www.google.com", "www.bbc.co.uk", "www.phantomjs.org"] 52 | 53 | RenderUrlsToFile arrayOfUrls, ((status, url, file) -> 54 | if status isnt "success" 55 | console.log "Unable to render '" + url + "'" 56 | else 57 | console.log "Rendered '" + url + "' at '" + file + "'" 58 | ), -> 59 | phantom.exit() 60 | 61 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/render_multi_url.js: -------------------------------------------------------------------------------- 1 | // Render Multiple URLs to file 2 | 3 | var RenderUrlsToFile, arrayOfUrls, system; 4 | 5 | system = require("system"); 6 | 7 | /* 8 | Render given urls 9 | @param array of URLs to render 10 | @param callbackPerUrl Function called after finishing each URL, including the last URL 11 | @param callbackFinal Function called after finishing everything 12 | */ 13 | RenderUrlsToFile = function(urls, callbackPerUrl, callbackFinal) { 14 | var getFilename, next, page, retrieve, urlIndex, webpage; 15 | urlIndex = 0; 16 | webpage = require("webpage"); 17 | page = null; 18 | getFilename = function() { 19 | return "rendermulti-" + urlIndex + ".png"; 20 | }; 21 | next = function(status, url, file) { 22 | page.close(); 23 | callbackPerUrl(status, url, file); 24 | return retrieve(); 25 | }; 26 | retrieve = function() { 27 | var url; 28 | if (urls.length > 0) { 29 | url = urls.shift(); 30 | urlIndex++; 31 | page = webpage.create(); 32 | page.viewportSize = { 33 | width: 800, 34 | height: 600 35 | }; 36 | page.settings.userAgent = "Phantom.js bot"; 37 | return page.open("http://" + url, function(status) { 38 | var file; 39 | file = getFilename(); 40 | if (status === "success") { 41 | return window.setTimeout((function() { 42 | page.render(file); 43 | return next(status, url, file); 44 | }), 200); 45 | } else { 46 | return next(status, url, file); 47 | } 48 | }); 49 | } else { 50 | return callbackFinal(); 51 | } 52 | }; 53 | return retrieve(); 54 | }; 55 | 56 | arrayOfUrls = null; 57 | 58 | if (system.args.length > 1) { 59 | arrayOfUrls = Array.prototype.slice.call(system.args, 1); 60 | } else { 61 | console.log("Usage: phantomjs render_multi_url.js [domain.name1, domain.name2, ...]"); 62 | arrayOfUrls = ["www.google.com", "www.bbc.co.uk", "www.phantomjs.org"]; 63 | } 64 | 65 | RenderUrlsToFile(arrayOfUrls, (function(status, url, file) { 66 | if (status !== "success") { 67 | return console.log("Unable to render '" + url + "'"); 68 | } else { 69 | return console.log("Rendered '" + url + "' at '" + file + "'"); 70 | } 71 | }), function() { 72 | return phantom.exit(); 73 | }); 74 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/run-jasmine.coffee: -------------------------------------------------------------------------------- 1 | system = require 'system' 2 | 3 | ## 4 | # Wait until the test condition is true or a timeout occurs. Useful for waiting 5 | # on a server response or for a ui change (fadeIn, etc.) to occur. 6 | # 7 | # @param testFx javascript condition that evaluates to a boolean, 8 | # it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 9 | # as a callback function. 10 | # @param onReady what to do when testFx condition is fulfilled, 11 | # it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 12 | # as a callback function. 13 | # @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. 14 | ## 15 | waitFor = (testFx, onReady, timeOutMillis=3000) -> 16 | start = new Date().getTime() 17 | condition = false 18 | f = -> 19 | if (new Date().getTime() - start < timeOutMillis) and not condition 20 | # If not time-out yet and condition not yet fulfilled 21 | condition = (if typeof testFx is 'string' then eval testFx else testFx()) #< defensive code 22 | else 23 | if not condition 24 | # If condition still not fulfilled (timeout but condition is 'false') 25 | console.log "'waitFor()' timeout" 26 | phantom.exit 1 27 | else 28 | # Condition fulfilled (timeout and/or condition is 'true') 29 | console.log "'waitFor()' finished in #{new Date().getTime() - start}ms." 30 | if typeof onReady is 'string' then eval onReady else onReady() #< Do what it's supposed to do once the condition is fulfilled 31 | clearInterval interval #< Stop this interval 32 | interval = setInterval f, 100 #< repeat check every 100ms 33 | 34 | if system.args.length isnt 2 35 | console.log 'Usage: run-jasmine.coffee URL' 36 | phantom.exit 1 37 | 38 | page = require('webpage').create() 39 | 40 | # Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") 41 | page.onConsoleMessage = (msg) -> 42 | console.log msg 43 | 44 | page.open system.args[1], (status) -> 45 | if status isnt 'success' 46 | console.log 'Unable to access network' 47 | phantom.exit() 48 | else 49 | waitFor -> 50 | page.evaluate -> 51 | if document.body.querySelector '.finished-at' 52 | return true 53 | return false 54 | , -> 55 | page.evaluate -> 56 | console.log document.body.querySelector('.description').innerText 57 | list = document.body.querySelectorAll('.failed > .description, .failed > .messages > .resultMessage') 58 | for el in list 59 | console.log el.innerText 60 | 61 | phantom.exit() 62 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/run-jasmine.js: -------------------------------------------------------------------------------- 1 | var system = require('system'); 2 | 3 | /** 4 | * Wait until the test condition is true or a timeout occurs. Useful for waiting 5 | * on a server response or for a ui change (fadeIn, etc.) to occur. 6 | * 7 | * @param testFx javascript condition that evaluates to a boolean, 8 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 9 | * as a callback function. 10 | * @param onReady what to do when testFx condition is fulfilled, 11 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 12 | * as a callback function. 13 | * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. 14 | */ 15 | function waitFor(testFx, onReady, timeOutMillis) { 16 | var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timeout is 3s 17 | start = new Date().getTime(), 18 | condition = false, 19 | interval = setInterval(function() { 20 | if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { 21 | // If not time-out yet and condition not yet fulfilled 22 | condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code 23 | } else { 24 | if(!condition) { 25 | // If condition still not fulfilled (timeout but condition is 'false') 26 | console.log("'waitFor()' timeout"); 27 | phantom.exit(1); 28 | } else { 29 | // Condition fulfilled (timeout and/or condition is 'true') 30 | console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); 31 | typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled 32 | clearInterval(interval); //< Stop this interval 33 | } 34 | } 35 | }, 100); //< repeat check every 100ms 36 | }; 37 | 38 | 39 | if (system.args.length !== 2) { 40 | console.log('Usage: run-jasmine.js URL'); 41 | phantom.exit(1); 42 | } 43 | 44 | var page = require('webpage').create(); 45 | 46 | // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") 47 | page.onConsoleMessage = function(msg) { 48 | console.log(msg); 49 | }; 50 | 51 | page.open(system.args[1], function(status){ 52 | if (status !== "success") { 53 | console.log("Unable to access network"); 54 | phantom.exit(); 55 | } else { 56 | waitFor(function(){ 57 | return page.evaluate(function(){ 58 | return document.body.querySelector('.symbolSummary .pending') === null 59 | }); 60 | }, function(){ 61 | var exitCode = page.evaluate(function(){ 62 | console.log(''); 63 | console.log(document.body.querySelector('.description').innerText); 64 | var list = document.body.querySelectorAll('.results > #details > .specDetail.failed'); 65 | if (list && list.length > 0) { 66 | console.log(''); 67 | console.log(list.length + ' test(s) FAILED:'); 68 | for (i = 0; i < list.length; ++i) { 69 | var el = list[i], 70 | desc = el.querySelector('.description'), 71 | msg = el.querySelector('.resultMessage.fail'); 72 | console.log(''); 73 | console.log(desc.innerText); 74 | console.log(msg.innerText); 75 | console.log(''); 76 | } 77 | return 1; 78 | } else { 79 | console.log(document.body.querySelector('.alert > .passingAlert.bar').innerText); 80 | return 0; 81 | } 82 | }); 83 | phantom.exit(exitCode); 84 | }); 85 | } 86 | }); 87 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/run-qunit.coffee: -------------------------------------------------------------------------------- 1 | system = require 'system' 2 | 3 | ## 4 | # Wait until the test condition is true or a timeout occurs. Useful for waiting 5 | # on a server response or for a ui change (fadeIn, etc.) to occur. 6 | # 7 | # @param testFx javascript condition that evaluates to a boolean, 8 | # it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 9 | # as a callback function. 10 | # @param onReady what to do when testFx condition is fulfilled, 11 | # it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 12 | # as a callback function. 13 | # @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. 14 | ## 15 | waitFor = (testFx, onReady, timeOutMillis=3000) -> 16 | start = new Date().getTime() 17 | condition = false 18 | f = -> 19 | if (new Date().getTime() - start < timeOutMillis) and not condition 20 | # If not time-out yet and condition not yet fulfilled 21 | condition = (if typeof testFx is 'string' then eval testFx else testFx()) #< defensive code 22 | else 23 | if not condition 24 | # If condition still not fulfilled (timeout but condition is 'false') 25 | console.log "'waitFor()' timeout" 26 | phantom.exit 1 27 | else 28 | # Condition fulfilled (timeout and/or condition is 'true') 29 | console.log "'waitFor()' finished in #{new Date().getTime() - start}ms." 30 | if typeof onReady is 'string' then eval onReady else onReady() #< Do what it's supposed to do once the condition is fulfilled 31 | clearInterval interval #< Stop this interval 32 | interval = setInterval f, 100 #< repeat check every 100ms 33 | 34 | if system.args.length isnt 2 35 | console.log 'Usage: run-qunit.coffee URL' 36 | phantom.exit 1 37 | 38 | page = require('webpage').create() 39 | 40 | # Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") 41 | page.onConsoleMessage = (msg) -> 42 | console.log msg 43 | 44 | page.open system.args[1], (status) -> 45 | if status isnt 'success' 46 | console.log 'Unable to access network' 47 | phantom.exit 1 48 | else 49 | waitFor -> 50 | page.evaluate -> 51 | el = document.getElementById 'qunit-testresult' 52 | if el and el.innerText.match 'completed' 53 | return true 54 | return false 55 | , -> 56 | failedNum = page.evaluate -> 57 | el = document.getElementById 'qunit-testresult' 58 | console.log el.innerText 59 | try 60 | return el.getElementsByClassName('failed')[0].innerHTML 61 | catch e 62 | return 10000 63 | 64 | phantom.exit if parseInt(failedNum, 10) > 0 then 1 else 0 65 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/run-qunit.js: -------------------------------------------------------------------------------- 1 | var system = require('system'); 2 | 3 | /** 4 | * Wait until the test condition is true or a timeout occurs. Useful for waiting 5 | * on a server response or for a ui change (fadeIn, etc.) to occur. 6 | * 7 | * @param testFx javascript condition that evaluates to a boolean, 8 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 9 | * as a callback function. 10 | * @param onReady what to do when testFx condition is fulfilled, 11 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or 12 | * as a callback function. 13 | * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. 14 | */ 15 | function waitFor(testFx, onReady, timeOutMillis) { 16 | var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timout is 3s 17 | start = new Date().getTime(), 18 | condition = false, 19 | interval = setInterval(function() { 20 | if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { 21 | // If not time-out yet and condition not yet fulfilled 22 | condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code 23 | } else { 24 | if(!condition) { 25 | // If condition still not fulfilled (timeout but condition is 'false') 26 | console.log("'waitFor()' timeout"); 27 | phantom.exit(1); 28 | } else { 29 | // Condition fulfilled (timeout and/or condition is 'true') 30 | console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); 31 | typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled 32 | clearInterval(interval); //< Stop this interval 33 | } 34 | } 35 | }, 100); //< repeat check every 250ms 36 | }; 37 | 38 | 39 | if (system.args.length !== 2) { 40 | console.log('Usage: run-qunit.js URL'); 41 | phantom.exit(1); 42 | } 43 | 44 | var page = require('webpage').create(); 45 | 46 | // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") 47 | page.onConsoleMessage = function(msg) { 48 | console.log(msg); 49 | }; 50 | 51 | page.open(system.args[1], function(status){ 52 | if (status !== "success") { 53 | console.log("Unable to access network"); 54 | phantom.exit(1); 55 | } else { 56 | waitFor(function(){ 57 | return page.evaluate(function(){ 58 | var el = document.getElementById('qunit-testresult'); 59 | if (el && el.innerText.match('completed')) { 60 | return true; 61 | } 62 | return false; 63 | }); 64 | }, function(){ 65 | var failedNum = page.evaluate(function(){ 66 | var el = document.getElementById('qunit-testresult'); 67 | console.log(el.innerText); 68 | try { 69 | return el.getElementsByClassName('failed')[0].innerHTML; 70 | } catch (e) { } 71 | return 10000; 72 | }); 73 | phantom.exit((parseInt(failedNum, 10) > 0) ? 1 : 0); 74 | }); 75 | } 76 | }); 77 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/scandir.coffee: -------------------------------------------------------------------------------- 1 | # List all the files in a Tree of Directories 2 | system = require 'system' 3 | 4 | if system.args.length != 2 5 | console.log "Usage: phantomjs scandir.coffee DIRECTORY_TO_SCAN" 6 | phantom.exit 1 7 | scanDirectory = (path) -> 8 | fs = require 'fs' 9 | if fs.exists(path) and fs.isFile(path) 10 | console.log path 11 | else if fs.isDirectory(path) 12 | fs.list(path).forEach (e) -> 13 | scanDirectory path + "/" + e if e != "." and e != ".." 14 | 15 | scanDirectory system.args[1] 16 | phantom.exit() 17 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/scandir.js: -------------------------------------------------------------------------------- 1 | // List all the files in a Tree of Directories 2 | var system = require('system'); 3 | 4 | if (system.args.length !== 2) { 5 | console.log("Usage: phantomjs scandir.js DIRECTORY_TO_SCAN"); 6 | phantom.exit(1); 7 | } 8 | 9 | var scanDirectory = function (path) { 10 | var fs = require('fs'); 11 | if (fs.exists(path) && fs.isFile(path)) { 12 | console.log(path); 13 | } else if (fs.isDirectory(path)) { 14 | fs.list(path).forEach(function (e) { 15 | if ( e !== "." && e !== ".." ) { //< Avoid loops 16 | scanDirectory(path + '/' + e); 17 | } 18 | }); 19 | } 20 | }; 21 | scanDirectory(system.args[1]); 22 | phantom.exit(); 23 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/seasonfood.coffee: -------------------------------------------------------------------------------- 1 | # Show BBC seasonal food list. 2 | 3 | window.cbfunc = (data) -> 4 | list = data.query.results.results.result 5 | names = ['January', 'February', 'March', 6 | 'April', 'May', 'June', 7 | 'July', 'August', 'September', 8 | 'October', 'November', 'December'] 9 | for item in list 10 | console.log [item.name.replace(/\s/ig, ' '), ':', 11 | names[item.atItsBestUntil], 'to', 12 | names[item.atItsBestFrom]].join(' ') 13 | phantom.exit() 14 | 15 | el = document.createElement 'script' 16 | el.src = 'http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20bbc.goodfood.seasonal%3B&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=window.cbfunc' 17 | document.body.appendChild el 18 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/seasonfood.js: -------------------------------------------------------------------------------- 1 | // Show BBC seasonal food list. 2 | 3 | var cbfunc = function (data) { 4 | var list = data.query.results.results.result, 5 | names = ['January', 'February', 'March', 6 | 'April', 'May', 'June', 7 | 'July', 'August', 'September', 8 | 'October', 'November', 'December']; 9 | list.forEach(function (item) { 10 | console.log([item.name.replace(/\s/ig, ' '), ':', 11 | names[item.atItsBestUntil], 'to', 12 | names[item.atItsBestFrom]].join(' ')); 13 | }); 14 | phantom.exit(); 15 | }; 16 | 17 | var el = document.createElement('script'); 18 | el.src = 'http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20bbc.goodfood.seasonal%3B&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=cbfunc'; 19 | document.body.appendChild(el); 20 | -------------------------------------------------------------------------------- /phantomjs-1.9.7-windows/examples/server.coffee: -------------------------------------------------------------------------------- 1 | page = require("webpage").create() 2 | server = require("webserver").create() 3 | system = require("system") 4 | host = undefined 5 | port = undefined 6 | if system.args.length isnt 2 7 | console.log "Usage: server.jspretty cool :)"
31 | response.close()
32 | )
33 | unless listening
34 | console.log "could not create web server listening on port " + port
35 | phantom.exit()
36 | url = "http://localhost:" + port + "/foo/bar.php?asdf=true"
37 | console.log "SENDING REQUEST TO:"
38 | console.log url
39 | page.open url, (status) ->
40 | if status isnt "success"
41 | console.log "FAIL to load the address"
42 | else
43 | console.log "GOT REPLY FROM SERVER:"
44 | console.log page.content
45 | phantom.exit()
46 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/server.js:
--------------------------------------------------------------------------------
1 | var page = require('webpage').create();
2 | var server = require('webserver').create();
3 | var system = require('system');
4 | var host, port;
5 |
6 | if (system.args.length !== 2) {
7 | console.log('Usage: server.js pretty cool :)");
25 | response.close();
26 | });
27 | if (!listening) {
28 | console.log("could not create web server listening on port " + port);
29 | phantom.exit();
30 | }
31 | var url = "http://localhost:" + port + "/foo/bar.php?asdf=true";
32 | console.log("SENDING REQUEST TO:");
33 | console.log(url);
34 | page.open(url, function (status) {
35 | if (status !== 'success') {
36 | console.log('FAIL to load the address');
37 | } else {
38 | console.log("GOT REPLY FROM SERVER:");
39 | console.log(page.content);
40 | }
41 | phantom.exit();
42 | });
43 | }
44 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/serverkeepalive.coffee:
--------------------------------------------------------------------------------
1 | port = undefined
2 | server = undefined
3 | service = undefined
4 | system = require("system")
5 | if system.args.length isnt 2
6 | console.log "Usage: serverkeepalive.js This is from PhantomJS web server. Request data: This is from PhantomJS web server. Request data:"
28 | response.write JSON.stringify(request, null, 4)
29 | response.write "
"
30 | response.write ""
31 | response.write ""
32 | response.close()
33 | )
34 | if service
35 | console.log "Web server running on port " + port
36 | else
37 | console.log "Error: Could not create web server listening on port " + port
38 | phantom.exit()
39 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/simpleserver.js:
--------------------------------------------------------------------------------
1 | var port, server, service,
2 | system = require('system');
3 |
4 | if (system.args.length !== 2) {
5 | console.log('Usage: simpleserver.js ');
29 | response.write(JSON.stringify(request, null, 4));
30 | response.write('
');
31 | response.write('');
32 | response.write('');
33 | response.close();
34 | });
35 |
36 | if (service) {
37 | console.log('Web server running on port ' + port);
38 | } else {
39 | console.log('Error: Could not create web server listening on port ' + port);
40 | phantom.exit();
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/sleepsort.coffee:
--------------------------------------------------------------------------------
1 | ###
2 | Sort integers from the command line in a very ridiculous way: leveraging timeouts :P
3 | ###
4 |
5 | system = require 'system'
6 |
7 | if system.args.length < 2
8 | console.log "Usage: phantomjs sleepsort.coffee PUT YOUR INTEGERS HERE SEPARATED BY SPACES"
9 | phantom.exit 1
10 | else
11 | sortedCount = 0
12 | args = Array.prototype.slice.call(system.args, 1)
13 | for int in args
14 | setTimeout (do (int) ->
15 | ->
16 | console.log int
17 | ++sortedCount
18 | phantom.exit() if sortedCount is args.length),
19 | int
20 |
21 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/sleepsort.js:
--------------------------------------------------------------------------------
1 | // sleepsort.js - Sort integers from the commandline in a very ridiculous way: leveraging timeouts :P
2 | var system = require('system');
3 |
4 | function sleepSort(array, callback) {
5 | var sortedCount = 0,
6 | i, len;
7 | for ( i = 0, len = array.length; i < len; ++i ) {
8 | setTimeout((function(j){
9 | return function() {
10 | console.log(array[j]);
11 | ++sortedCount;
12 | (len === sortedCount) && callback();
13 | };
14 | }(i)), array[i]);
15 | }
16 | }
17 |
18 | if ( system.args < 2 ) {
19 | console.log("Usage: phantomjs sleepsort.js PUT YOUR INTEGERS HERE SEPARATED BY SPACES");
20 | phantom.exit(1);
21 | } else {
22 | sleepSort(Array.prototype.slice.call(system.args, 1), function() {
23 | phantom.exit();
24 | });
25 | }
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/stdin-stdout-stderr.coffee:
--------------------------------------------------------------------------------
1 | system = require 'system'
2 |
3 | system.stdout.write 'Hello, system.stdout.write!'
4 | system.stdout.writeLine '\nHello, system.stdout.writeLine!'
5 |
6 | system.stderr.write 'Hello, system.stderr.write!'
7 | system.stderr.writeLine '\nHello, system.stderr.writeLine!'
8 |
9 | system.stdout.writeLine 'system.stdin.readLine(): '
10 | line = system.stdin.readLine()
11 | system.stdout.writeLine JSON.stringify line
12 |
13 | # This is essentially a `readAll`
14 | system.stdout.writeLine 'system.stdin.read(5): (ctrl+D to end)'
15 | input = system.stdin.read 5
16 | system.stdout.writeLine JSON.stringify input
17 |
18 | phantom.exit 0
19 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/stdin-stdout-stderr.js:
--------------------------------------------------------------------------------
1 | var system = require('system');
2 |
3 | system.stdout.write('Hello, system.stdout.write!');
4 | system.stdout.writeLine('\nHello, system.stdout.writeLine!');
5 |
6 | system.stderr.write('Hello, system.stderr.write!');
7 | system.stderr.writeLine('\nHello, system.stderr.writeLine!');
8 |
9 | system.stdout.writeLine('system.stdin.readLine(): ');
10 | var line = system.stdin.readLine();
11 | system.stdout.writeLine(JSON.stringify(line));
12 |
13 | // This is essentially a `readAll`
14 | system.stdout.writeLine('system.stdin.read(5): (ctrl+D to end)');
15 | var input = system.stdin.read(5);
16 | system.stdout.writeLine(JSON.stringify(input));
17 |
18 | phantom.exit(0);
19 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/technews.coffee:
--------------------------------------------------------------------------------
1 | page = require('webpage').create()
2 |
3 | page.viewportSize = { width: 320, height: 480 }
4 |
5 | page.open 'http://news.google.com/news/i/section?&topic=t',
6 | (status) ->
7 | if status isnt 'success'
8 | console.log 'Unable to access the network!'
9 | else
10 | page.evaluate ->
11 | body = document.body
12 | body.style.backgroundColor = '#fff'
13 | body.querySelector('div#title-block').style.display = 'none'
14 | body.querySelector('form#edition-picker-form')
15 | .parentElement.parentElement.style.display = 'none'
16 | page.render 'technews.png'
17 | phantom.exit()
18 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/technews.js:
--------------------------------------------------------------------------------
1 | var page = require('webpage').create();
2 | page.viewportSize = { width: 320, height: 480 };
3 | page.open('http://news.google.com/news/i/section?&topic=t', function (status) {
4 | if (status !== 'success') {
5 | console.log('Unable to access the network!');
6 | } else {
7 | page.evaluate(function () {
8 | var body = document.body;
9 | body.style.backgroundColor = '#fff';
10 | body.querySelector('div#title-block').style.display = 'none';
11 | body.querySelector('form#edition-picker-form').parentElement.parentElement.style.display = 'none';
12 | });
13 | page.render('technews.png');
14 | }
15 | phantom.exit();
16 | });
17 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/tweets.coffee:
--------------------------------------------------------------------------------
1 | # Get twitter status for given account (or for the default one, "PhantomJS")
2 |
3 | page = require('webpage').create()
4 | system = require 'system'
5 | twitterId = 'PhantomJS' #< default value
6 |
7 | # Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this")
8 | page.onConsoleMessage = (msg) ->
9 | console.log msg
10 |
11 | # Print usage message, if no twitter ID is passed
12 | if system.args.length < 2
13 | console.log 'Usage: tweets.coffee [twitter ID]'
14 | else
15 | twitterId = system.args[1]
16 |
17 | # Heading
18 | console.log "*** Latest tweets from @#{twitterId} ***\n"
19 |
20 | # Open Twitter Mobile and, onPageLoad, do...
21 | page.open encodeURI("http://mobile.twitter.com/#{twitterId}"), (status) ->
22 | # Check for page load success
23 | if status isnt 'success'
24 | console.log 'Unable to access network'
25 | else
26 | # Execute some DOM inspection within the page context
27 | page.evaluate ->
28 | list = document.querySelectorAll 'div.tweet-text'
29 | for i, j in list
30 | console.log "#{j + 1}: #{i.innerText}"
31 | phantom.exit()
32 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/tweets.js:
--------------------------------------------------------------------------------
1 | // Get twitter status for given account (or for the default one, "PhantomJS")
2 |
3 | var page = require('webpage').create(),
4 | system = require('system'),
5 | twitterId = "PhantomJS"; //< default value
6 |
7 | // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this")
8 | page.onConsoleMessage = function(msg) {
9 | console.log(msg);
10 | };
11 |
12 | // Print usage message, if no twitter ID is passed
13 | if (system.args.length < 2) {
14 | console.log("Usage: tweets.js [twitter ID]");
15 | } else {
16 | twitterId = system.args[1];
17 | }
18 |
19 | // Heading
20 | console.log("*** Latest tweets from @" + twitterId + " ***\n");
21 |
22 | // Open Twitter Mobile and, onPageLoad, do...
23 | page.open(encodeURI("http://mobile.twitter.com/" + twitterId), function (status) {
24 | // Check for page load success
25 | if (status !== "success") {
26 | console.log("Unable to access network");
27 | } else {
28 | // Execute some DOM inspection within the page context
29 | page.evaluate(function() {
30 | var list = document.querySelectorAll('div.tweet-text');
31 | for (var i = 0; i < list.length; ++i) {
32 | console.log((i + 1) + ": " + list[i].innerText);
33 | }
34 | });
35 | }
36 | phantom.exit();
37 | });
38 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/universe.js:
--------------------------------------------------------------------------------
1 | // This is to be used by "module.js" (and "module.coffee") example(s).
2 | // There should NOT be a "universe.coffee" as only 1 of the 2 would
3 | // ever be loaded unless the file extension was specified.
4 |
5 | exports.answer = 42;
6 |
7 | exports.start = function () {
8 | console.log('Starting the universe....');
9 | }
10 |
11 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/unrandomize.coffee:
--------------------------------------------------------------------------------
1 | # Modify global object at the page initialization.
2 | # In this example, effectively Math.random() always returns 0.42.
3 |
4 | page = require('webpage').create()
5 | page.onInitialized = ->
6 | page.evaluate ->
7 | Math.random = ->
8 | 42 / 100
9 |
10 | page.open "http://ariya.github.com/js/random/", (status) ->
11 | if status != "success"
12 | console.log "Network error."
13 | else
14 | console.log page.evaluate(->
15 | document.getElementById("numbers").textContent
16 | )
17 | phantom.exit()
18 |
19 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/unrandomize.js:
--------------------------------------------------------------------------------
1 | // Modify global object at the page initialization.
2 | // In this example, effectively Math.random() always returns 0.42.
3 |
4 | var page = require('webpage').create();
5 |
6 | page.onInitialized = function () {
7 | page.evaluate(function () {
8 | Math.random = function() {
9 | return 42 / 100;
10 | };
11 | });
12 | };
13 |
14 | page.open('http://ariya.github.com/js/random/', function (status) {
15 | var result;
16 | if (status !== 'success') {
17 | console.log('Network error.');
18 | } else {
19 | console.log(page.evaluate(function () {
20 | return document.getElementById('numbers').textContent;
21 | }));
22 | }
23 | phantom.exit();
24 | });
25 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/useragent.coffee:
--------------------------------------------------------------------------------
1 | page = require('webpage').create()
2 |
3 | console.log 'The default user agent is ' + page.settings.userAgent
4 |
5 | page.settings.userAgent = 'SpecialAgent'
6 | page.open 'http://www.httpuseragent.org', (status) ->
7 | if status isnt 'success'
8 | console.log 'Unable to access network'
9 | else
10 | console.log page.evaluate -> document.getElementById('myagent').innerText
11 | phantom.exit()
12 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/useragent.js:
--------------------------------------------------------------------------------
1 | var page = require('webpage').create();
2 | console.log('The default user agent is ' + page.settings.userAgent);
3 | page.settings.userAgent = 'SpecialAgent';
4 | page.open('http://www.httpuseragent.org', function (status) {
5 | if (status !== 'success') {
6 | console.log('Unable to access network');
7 | } else {
8 | var ua = page.evaluate(function () {
9 | return document.getElementById('myagent').innerText;
10 | });
11 | console.log(ua);
12 | }
13 | phantom.exit();
14 | });
15 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/version.coffee:
--------------------------------------------------------------------------------
1 | console.log 'using PhantomJS version ' +
2 | phantom.version.major + '.' +
3 | phantom.version.minor + '.' +
4 | phantom.version.patch
5 | phantom.exit()
6 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/version.js:
--------------------------------------------------------------------------------
1 | console.log('using PhantomJS version ' +
2 | phantom.version.major + '.' +
3 | phantom.version.minor + '.' +
4 | phantom.version.patch);
5 | phantom.exit();
6 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/waitfor.coffee:
--------------------------------------------------------------------------------
1 | ##
2 | # Wait until the test condition is true or a timeout occurs. Useful for waiting
3 | # on a server response or for a ui change (fadeIn, etc.) to occur.
4 | #
5 | # @param testFx javascript condition that evaluates to a boolean,
6 | # it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
7 | # as a callback function.
8 | # @param onReady what to do when testFx condition is fulfilled,
9 | # it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
10 | # as a callback function.
11 | # @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
12 | ##
13 | waitFor = (testFx, onReady, timeOutMillis=3000) ->
14 | start = new Date().getTime()
15 | condition = false
16 | f = ->
17 | if (new Date().getTime() - start < timeOutMillis) and not condition
18 | # If not time-out yet and condition not yet fulfilled
19 | condition = (if typeof testFx is 'string' then eval testFx else testFx()) #< defensive code
20 | else
21 | if not condition
22 | # If condition still not fulfilled (timeout but condition is 'false')
23 | console.log "'waitFor()' timeout"
24 | phantom.exit 1
25 | else
26 | # Condition fulfilled (timeout and/or condition is 'true')
27 | console.log "'waitFor()' finished in #{new Date().getTime() - start}ms."
28 | if typeof onReady is 'string' then eval onReady else onReady() #< Do what it's supposed to do once the condition is fulfilled
29 | clearInterval interval #< Stop this interval
30 | interval = setInterval f, 250 #< repeat check every 250ms
31 |
32 |
33 | page = require('webpage').create()
34 |
35 | # Open Twitter on 'sencha' profile and, onPageLoad, do...
36 | page.open 'http://twitter.com/#!/sencha', (status) ->
37 | # Check for page load success
38 | if status isnt 'success'
39 | console.log 'Unable to access network'
40 | else
41 | # Wait for 'signin-dropdown' to be visible
42 | waitFor ->
43 | # Check in the page if a specific element is now visible
44 | page.evaluate ->
45 | $('#signin-dropdown').is ':visible'
46 | , ->
47 | console.log 'The sign-in dialog should be visible now.'
48 | phantom.exit()
49 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/waitfor.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Wait until the test condition is true or a timeout occurs. Useful for waiting
3 | * on a server response or for a ui change (fadeIn, etc.) to occur.
4 | *
5 | * @param testFx javascript condition that evaluates to a boolean,
6 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
7 | * as a callback function.
8 | * @param onReady what to do when testFx condition is fulfilled,
9 | * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
10 | * as a callback function.
11 | * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
12 | */
13 | function waitFor(testFx, onReady, timeOutMillis) {
14 | var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
15 | start = new Date().getTime(),
16 | condition = false,
17 | interval = setInterval(function() {
18 | if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
19 | // If not time-out yet and condition not yet fulfilled
20 | condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
21 | } else {
22 | if(!condition) {
23 | // If condition still not fulfilled (timeout but condition is 'false')
24 | console.log("'waitFor()' timeout");
25 | phantom.exit(1);
26 | } else {
27 | // Condition fulfilled (timeout and/or condition is 'true')
28 | console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
29 | typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
30 | clearInterval(interval); //< Stop this interval
31 | }
32 | }
33 | }, 250); //< repeat check every 250ms
34 | };
35 |
36 |
37 | var page = require('webpage').create();
38 |
39 | // Open Twitter on 'sencha' profile and, onPageLoad, do...
40 | page.open("http://twitter.com/#!/sencha", function (status) {
41 | // Check for page load success
42 | if (status !== "success") {
43 | console.log("Unable to access network");
44 | } else {
45 | // Wait for 'signin-dropdown' to be visible
46 | waitFor(function() {
47 | // Check in the page if a specific element is now visible
48 | return page.evaluate(function() {
49 | return $("#signin-dropdown").is(":visible");
50 | });
51 | }, function() {
52 | console.log("The sign-in dialog should be visible now.");
53 | phantom.exit();
54 | });
55 | }
56 | });
57 |
58 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/walk_through_frames.coffee:
--------------------------------------------------------------------------------
1 | pageTitle = (page) ->
2 | page.evaluate ->
3 | window.document.title
4 | setPageTitle = (page, newTitle) ->
5 | page.evaluate ((newTitle) ->
6 | window.document.title = newTitle
7 | ), newTitle
8 | p = require("webpage").create()
9 | p.open "../test/webpage-spec-frames/index.html", (status) ->
10 | console.log "pageTitle(): " + pageTitle(p)
11 | console.log "currentFrameName(): " + p.currentFrameName()
12 | console.log "childFramesCount(): " + p.childFramesCount()
13 | console.log "childFramesName(): " + p.childFramesName()
14 | console.log "setPageTitle(CURRENT TITLE+'-visited')"
15 | setPageTitle p, pageTitle(p) + "-visited"
16 | console.log ""
17 | console.log "p.switchToChildFrame(\"frame1\"): " + p.switchToChildFrame("frame1")
18 | console.log "pageTitle(): " + pageTitle(p)
19 | console.log "currentFrameName(): " + p.currentFrameName()
20 | console.log "childFramesCount(): " + p.childFramesCount()
21 | console.log "childFramesName(): " + p.childFramesName()
22 | console.log "setPageTitle(CURRENT TITLE+'-visited')"
23 | setPageTitle p, pageTitle(p) + "-visited"
24 | console.log ""
25 | console.log "p.switchToChildFrame(\"frame1-2\"): " + p.switchToChildFrame("frame1-2")
26 | console.log "pageTitle(): " + pageTitle(p)
27 | console.log "currentFrameName(): " + p.currentFrameName()
28 | console.log "childFramesCount(): " + p.childFramesCount()
29 | console.log "childFramesName(): " + p.childFramesName()
30 | console.log "setPageTitle(CURRENT TITLE+'-visited')"
31 | setPageTitle p, pageTitle(p) + "-visited"
32 | console.log ""
33 | console.log "p.switchToParentFrame(): " + p.switchToParentFrame()
34 | console.log "pageTitle(): " + pageTitle(p)
35 | console.log "currentFrameName(): " + p.currentFrameName()
36 | console.log "childFramesCount(): " + p.childFramesCount()
37 | console.log "childFramesName(): " + p.childFramesName()
38 | console.log "setPageTitle(CURRENT TITLE+'-visited')"
39 | setPageTitle p, pageTitle(p) + "-visited"
40 | console.log ""
41 | console.log "p.switchToChildFrame(0): " + p.switchToChildFrame(0)
42 | console.log "pageTitle(): " + pageTitle(p)
43 | console.log "currentFrameName(): " + p.currentFrameName()
44 | console.log "childFramesCount(): " + p.childFramesCount()
45 | console.log "childFramesName(): " + p.childFramesName()
46 | console.log "setPageTitle(CURRENT TITLE+'-visited')"
47 | setPageTitle p, pageTitle(p) + "-visited"
48 | console.log ""
49 | console.log "p.switchToMainFrame()"
50 | p.switchToMainFrame()
51 | console.log "pageTitle(): " + pageTitle(p)
52 | console.log "currentFrameName(): " + p.currentFrameName()
53 | console.log "childFramesCount(): " + p.childFramesCount()
54 | console.log "childFramesName(): " + p.childFramesName()
55 | console.log "setPageTitle(CURRENT TITLE+'-visited')"
56 | setPageTitle p, pageTitle(p) + "-visited"
57 | console.log ""
58 | console.log "p.switchToChildFrame(\"frame2\"): " + p.switchToChildFrame("frame2")
59 | console.log "pageTitle(): " + pageTitle(p)
60 | console.log "currentFrameName(): " + p.currentFrameName()
61 | console.log "childFramesCount(): " + p.childFramesCount()
62 | console.log "childFramesName(): " + p.childFramesName()
63 | console.log "setPageTitle(CURRENT TITLE+'-visited')"
64 | setPageTitle p, pageTitle(p) + "-visited"
65 | console.log ""
66 | phantom.exit()
67 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/walk_through_frames.js:
--------------------------------------------------------------------------------
1 | var p = require("webpage").create();
2 |
3 | function pageTitle(page) {
4 | return page.evaluate(function(){
5 | return window.document.title;
6 | });
7 | }
8 |
9 | function setPageTitle(page, newTitle) {
10 | page.evaluate(function(newTitle){
11 | window.document.title = newTitle;
12 | }, newTitle);
13 | }
14 |
15 | p.open("../test/webpage-spec-frames/index.html", function(status) {
16 | console.log("pageTitle(): " + pageTitle(p));
17 | console.log("currentFrameName(): "+p.currentFrameName());
18 | console.log("childFramesCount(): "+p.childFramesCount());
19 | console.log("childFramesName(): "+p.childFramesName());
20 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited");
21 | console.log("");
22 |
23 | console.log("p.switchToChildFrame(\"frame1\"): "+p.switchToChildFrame("frame1"));
24 | console.log("pageTitle(): " + pageTitle(p));
25 | console.log("currentFrameName(): "+p.currentFrameName());
26 | console.log("childFramesCount(): "+p.childFramesCount());
27 | console.log("childFramesName(): "+p.childFramesName());
28 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited");
29 | console.log("");
30 |
31 | console.log("p.switchToChildFrame(\"frame1-2\"): "+p.switchToChildFrame("frame1-2"));
32 | console.log("pageTitle(): " + pageTitle(p));
33 | console.log("currentFrameName(): "+p.currentFrameName());
34 | console.log("childFramesCount(): "+p.childFramesCount());
35 | console.log("childFramesName(): "+p.childFramesName());
36 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited");
37 | console.log("");
38 |
39 | console.log("p.switchToParentFrame(): "+p.switchToParentFrame());
40 | console.log("pageTitle(): " + pageTitle(p));
41 | console.log("currentFrameName(): "+p.currentFrameName());
42 | console.log("childFramesCount(): "+p.childFramesCount());
43 | console.log("childFramesName(): "+p.childFramesName());
44 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited");
45 | console.log("");
46 |
47 | console.log("p.switchToChildFrame(0): "+p.switchToChildFrame(0));
48 | console.log("pageTitle(): " + pageTitle(p));
49 | console.log("currentFrameName(): "+p.currentFrameName());
50 | console.log("childFramesCount(): "+p.childFramesCount());
51 | console.log("childFramesName(): "+p.childFramesName());
52 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited");
53 | console.log("");
54 |
55 | console.log("p.switchToMainFrame()"); p.switchToMainFrame();
56 | console.log("pageTitle(): " + pageTitle(p));
57 | console.log("currentFrameName(): "+p.currentFrameName());
58 | console.log("childFramesCount(): "+p.childFramesCount());
59 | console.log("childFramesName(): "+p.childFramesName());
60 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited");
61 | console.log("");
62 |
63 | console.log("p.switchToChildFrame(\"frame2\"): "+p.switchToChildFrame("frame2"));
64 | console.log("pageTitle(): " + pageTitle(p));
65 | console.log("currentFrameName(): "+p.currentFrameName());
66 | console.log("childFramesCount(): "+p.childFramesCount());
67 | console.log("childFramesName(): "+p.childFramesName());
68 | console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited");
69 | console.log("");
70 |
71 | phantom.exit();
72 | });
73 |
74 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/weather.coffee:
--------------------------------------------------------------------------------
1 | page = require('webpage').create()
2 | system = require 'system'
3 |
4 | city = 'Mountain View, California'; # default
5 | if system.args.length > 1
6 | city = Array.prototype.slice.call(system.args, 1).join(' ')
7 | url = encodeURI 'http://api.openweathermap.org/data/2.1/find/name?q=' + city
8 |
9 | console.log 'Checking weather condition for', city, '...'
10 |
11 | page.open url, (status) ->
12 | if status isnt 'success'
13 | console.log 'Error: Unable to access network!'
14 | else
15 | result = page.evaluate ->
16 | return document.body.innerText
17 | try
18 | data = JSON.parse result
19 | data = data.list[0]
20 | console.log ''
21 | console.log 'City:', data.name
22 | console.log 'Condition:', data.weather.map (entry) ->
23 | return entry.main
24 | console.log 'Temperature:', Math.round(data.main.temp - 273.15), 'C'
25 | console.log 'Humidity:', Math.round(data.main.humidity), '%'
26 | catch e
27 | console.log 'Error:', e.toString()
28 |
29 | phantom.exit()
30 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/examples/weather.js:
--------------------------------------------------------------------------------
1 | var page = require('webpage').create(),
2 | system = require('system'),
3 | city,
4 | url;
5 |
6 | city = 'Mountain View, California'; // default
7 | if (system.args.length > 1) {
8 | city = Array.prototype.slice.call(system.args, 1).join(' ');
9 | }
10 | url = encodeURI('http://api.openweathermap.org/data/2.1/find/name?q=' + city);
11 |
12 | console.log('Checking weather condition for', city, '...');
13 |
14 | page.open(url, function(status) {
15 | var result, data;
16 | if (status !== 'success') {
17 | console.log('Error: Unable to access network!');
18 | } else {
19 | result = page.evaluate(function () {
20 | return document.body.innerText;
21 | });
22 | try {
23 | data = JSON.parse(result);
24 | data = data.list[0];
25 | console.log('');
26 | console.log('City:', data.name);
27 | console.log('Condition:', data.weather.map(function(entry) {
28 | return entry.main;
29 | }).join(', '));
30 | console.log('Temperature:', Math.round(data.main.temp - 273.15), 'C');
31 | console.log('Humidity:', Math.round(data.main.humidity), '%');
32 | } catch (e) {
33 | console.log('Error:', e.toString());
34 | }
35 | }
36 | phantom.exit();
37 | });
38 |
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/phantomjs.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/liangyangtao/ubk_weixinbysogou/93fff8b83d702f222a7a93a0e1fba24cb88174b8/phantomjs-1.9.7-windows/phantomjs.exe
--------------------------------------------------------------------------------
/phantomjs-1.9.7-windows/third-party.txt:
--------------------------------------------------------------------------------
1 | This document contains the list of Third Party Software included with
2 | PhantomJS, along with the license information.
3 |
4 | Third Party Software may impose additional restrictions and it is the
5 | user's responsibility to ensure that they have met the licensing
6 | requirements of PhantomJS and the relevant license of the Third Party
7 | Software they are using.
8 |
9 | Qt - http://qt-project.org/
10 | License: GNU Lesser General Public License (LGPL) version 2.1.
11 | Reference: http://qt-project.org/doc/qt-4.8/lgpl.html.
12 |
13 | WebKit - http://www.webkit.org/
14 | License: GNU Lesser General Public License (LGPL) version 2.1 and BSD.
15 | Reference: http://www.webkit.org/coding/lgpl-license.html and
16 | http://www.webkit.org/coding/bsd-license.html.
17 |
18 | Mongoose - https://github.com/cesanta/mongoose
19 | License: MIT
20 | Reference: https://github.com/cesanta/mongoose/commit/abbf27338ef554cce0281ac157aa71a9c1b82a55
21 |
22 | Breakpad - http://code.google.com/p/google-breakpad/
23 | License: BSD.
24 | Reference: http://code.google.com/p/google-breakpad/source/browse/trunk/COPYING.
25 |
26 | OpenSSL - http://www.openssl.org/
27 | License: OpenSSL License, SSLeay License.
28 | Reference: http://www.openssl.org/source/license.html.
29 |
30 | Linenoise - https://github.com/tadmarshall/linenoise
31 | License: BSD.
32 | Reference: https://github.com/tadmarshall/linenoise/blob/master/linenoise.h.
33 |
34 | QCommandLine - http://xf.iksaif.net/dev/qcommandline.html
35 | License: GNU Lesser General Public License (LGPL) version 2.1.
36 | Reference: http://dev.iksaif.net/projects/qcommandline/repository/revisions/master/entry/COPYING
37 |
38 | CoffeeScript - http://coffeescript.org/
39 | License: MIT.
40 | Reference: https://github.com/jashkenas/coffee-script/blob/master/README.
41 |
42 | GIFLIB - http://giflib.sourceforge.net/
43 | License: MIT
44 | Reference: http://giflib.cvs.sourceforge.net/viewvc/giflib/giflib/COPYING
45 |
46 | wkhtmlpdf - http://code.google.com/p/wkhtmltopdf/
47 | License: GNU Lesser General Public License (LGPL)
48 | Reference: http://code.google.com/p/wkhtmltopdf/
49 |
--------------------------------------------------------------------------------
/src/main/java/com/unbank/Constants.java:
--------------------------------------------------------------------------------
1 | package com.unbank;
2 |
3 | import org.springframework.stereotype.Component;
4 |
5 | @Component
6 | public class Constants {
7 |
8 | public static Integer SERVERPORT;
9 | public static String SERVERIP;
10 | public static boolean USE_SSL;
11 |
12 | public static int HEARTBEATRATE;
13 | public static String HEARTBEATREQUEST = "HEARTBEATREQUEST";
14 | public static String HEARTBEATRESPONSE = "HEARTBEATRESPONSE";
15 | public static int HEART_TIMEOUT;
16 | public static int CLENT_TIMEOUT;
17 |
18 | public static Boolean ISTANCHUANG;
19 |
20 | public void init() {
21 |
22 | }
23 |
24 | public static Integer getSERVERPORT() {
25 | return SERVERPORT;
26 | }
27 |
28 | public static void setSERVERPORT(Integer sERVERPORT) {
29 | SERVERPORT = sERVERPORT;
30 | }
31 |
32 | public static String getSERVERIP() {
33 | return SERVERIP;
34 | }
35 |
36 | public static void setSERVERIP(String sERVERIP) {
37 | SERVERIP = sERVERIP;
38 | }
39 |
40 | public static boolean isUSE_SSL() {
41 | return USE_SSL;
42 | }
43 |
44 | public static void setUSE_SSL(boolean uSE_SSL) {
45 | USE_SSL = uSE_SSL;
46 | }
47 |
48 | public static int getHEARTBEATRATE() {
49 | return HEARTBEATRATE;
50 | }
51 |
52 | public static void setHEARTBEATRATE(int hEARTBEATRATE) {
53 | HEARTBEATRATE = hEARTBEATRATE;
54 | }
55 |
56 | public static String getHEARTBEATREQUEST() {
57 | return HEARTBEATREQUEST;
58 | }
59 |
60 | public static void setHEARTBEATREQUEST(String hEARTBEATREQUEST) {
61 | HEARTBEATREQUEST = hEARTBEATREQUEST;
62 | }
63 |
64 | public static String getHEARTBEATRESPONSE() {
65 | return HEARTBEATRESPONSE;
66 | }
67 |
68 | public static void setHEARTBEATRESPONSE(String hEARTBEATRESPONSE) {
69 | HEARTBEATRESPONSE = hEARTBEATRESPONSE;
70 | }
71 |
72 | public static int getHEART_TIMEOUT() {
73 | return HEART_TIMEOUT;
74 | }
75 |
76 | public static void setHEART_TIMEOUT(int hEART_TIMEOUT) {
77 | HEART_TIMEOUT = hEART_TIMEOUT;
78 | }
79 |
80 | public static int getCLENT_TIMEOUT() {
81 | return CLENT_TIMEOUT;
82 | }
83 |
84 | public static void setCLENT_TIMEOUT(int cLENT_TIMEOUT) {
85 | CLENT_TIMEOUT = cLENT_TIMEOUT;
86 | }
87 |
88 | public static Boolean getISTANCHUANG() {
89 | return ISTANCHUANG;
90 | }
91 |
92 | public static void setISTANCHUANG(Boolean iSTANCHUANG) {
93 | ISTANCHUANG = iSTANCHUANG;
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/src/main/java/com/unbank/Spider.java:
--------------------------------------------------------------------------------
1 | package com.unbank;
2 |
3 | import org.apache.commons.logging.Log;
4 | import org.apache.commons.logging.LogFactory;
5 | import org.apache.log4j.PropertyConfigurator;
6 | import org.springframework.context.support.ClassPathXmlApplicationContext;
7 |
8 | public class Spider {
9 | private static Log logger = LogFactory.getLog(Spider.class);
10 | static {
11 | // 启动日志
12 | try {
13 | PropertyConfigurator.configure(Spider.class.getClassLoader()
14 | .getResource("").toURI().getPath()
15 | + "log4j.properties");
16 | logger.info("---日志系统启动成功---");
17 | } catch (Exception e) {
18 | logger.error("日志系统启动失败:", e);
19 | }
20 | }
21 |
22 | public static void main(String[] args) {
23 | new ClassPathXmlApplicationContext(
24 | new String[] { "applicationContext.xml" });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/unbank/entity/News.java:
--------------------------------------------------------------------------------
1 | package com.unbank.entity;
2 |
3 | public class News {
4 |
5 | public int id;
6 | public String title;
7 | public String content;
8 | public Long time;
9 | public String url;
10 | public Long crawlTime;
11 |
12 | public int getId() {
13 | return id;
14 | }
15 |
16 | public void setId(int id) {
17 | this.id = id;
18 | }
19 |
20 | public String getTitle() {
21 | return title;
22 | }
23 |
24 | public void setTitle(String title) {
25 | this.title = title;
26 | }
27 |
28 | public String getContent() {
29 | return content;
30 | }
31 |
32 | public void setContent(String content) {
33 | this.content = content;
34 | }
35 |
36 | public Long getTime() {
37 | return time;
38 | }
39 |
40 | public void setTime(Long time) {
41 | this.time = time;
42 | }
43 |
44 | public String getUrl() {
45 | return url;
46 | }
47 |
48 | public void setUrl(String url) {
49 | this.url = url;
50 | }
51 |
52 | public Long getCrawlTime() {
53 | return crawlTime;
54 | }
55 |
56 | public void setCrawlTime(Long crawlTime) {
57 | this.crawlTime = crawlTime;
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/com/unbank/entity/Weixin.java:
--------------------------------------------------------------------------------
1 | package com.unbank.entity;
2 |
3 | public class Weixin extends News {
4 |
5 | public String weixin_account;
6 |
7 | public String openid;
8 |
9 | public String getWeixin_account() {
10 | return weixin_account;
11 | }
12 |
13 | public void setWeixin_account(String weixin_account) {
14 | this.weixin_account = weixin_account;
15 | }
16 |
17 | public String getOpenid() {
18 | return openid;
19 | }
20 |
21 | public void setOpenid(String openid) {
22 | this.openid = openid;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/com/unbank/fetch/PhantomjsFetcher.java:
--------------------------------------------------------------------------------
1 | package com.unbank.fetch;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | import org.apache.commons.logging.Log;
6 | import org.apache.commons.logging.LogFactory;
7 | import org.openqa.selenium.JavascriptExecutor;
8 | import org.openqa.selenium.WebDriver;
9 | import org.openqa.selenium.phantomjs.PhantomJSDriver;
10 | import org.openqa.selenium.phantomjs.PhantomJSDriverService;
11 | import org.openqa.selenium.remote.CapabilityType;
12 | import org.openqa.selenium.remote.DesiredCapabilities;
13 | import org.openqa.selenium.support.ui.ExpectedCondition;
14 | import org.openqa.selenium.support.ui.Wait;
15 | import org.openqa.selenium.support.ui.WebDriverWait;
16 |
17 | public class PhantomjsFetcher {
18 |
19 | private static Log logger = LogFactory.getLog(PhantomjsFetcher.class);
20 |
21 | private static WebDriver driver;
22 |
23 | public static synchronized WebDriver getInstenceDriver() {
24 | if (driver == null) {
25 | DesiredCapabilities caps = new DesiredCapabilities();
26 | caps.setJavascriptEnabled(true);
27 | caps.setCapability(
28 | PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
29 | "phantomjs-1.9.7-windows/phantomjs.exe");
30 | driver = new PhantomJSDriver(caps);
31 | long timeout = 5000;
32 | TimeUnit timeUnit = TimeUnit.MILLISECONDS;
33 | driver.manage().timeouts().pageLoadTimeout(timeout, timeUnit);
34 | }
35 | return driver;
36 | }
37 |
38 | public PhantomjsFetcher() {
39 | getInstenceDriver();
40 | }
41 |
42 | public static String get(String url) {
43 | getInstenceDriver();
44 | String html = null;
45 | try {
46 | driver.get(url);
47 | waitForPageLoaded(driver);
48 | html = driver.getPageSource();
49 |
50 | } catch (Exception e) {
51 |
52 | if (e instanceof org.openqa.selenium.TimeoutException) {
53 | System.out.println(((JavascriptExecutor) driver)
54 | .executeScript("return document.readyState"));
55 | logger.info(url + " " + "读取超时");
56 | } else {
57 | e.printStackTrace();
58 | }
59 | } finally {
60 | html = driver.getPageSource();
61 | }
62 | return html;
63 | }
64 |
65 | public void scroll() {
66 | ((JavascriptExecutor) driver)
67 | .executeScript("window.scrollTo(0,document.body.scrollHeight)");
68 | }
69 |
70 | public static void waitForPageLoaded(WebDriver driver) {
71 | ExpectedCondition