Phantomjs - Roughly Useful Tips

Code Context
There are mainly 2 contexts inward PhantomJS program: first, the PhantomJS programme itself; second, the webpage opened upwardly inward your headless browser, i.e., access to the DOM.

How tin I execute JavaScript on the given webpage itself within PhantomJS?
The solution is page.evaluate (where page is the variable representing the electrical current page "open" inward your headless browser). page.evaluate takes, every bit argument, a role to-be executed inward the context of the webpage. It tin render a outcome from the webpage dorsum to your PhantomJS program. For example, that you'd similar to watch the text of an chemical component subdivision on the electrical current page alongside ID "foo":
 var foo = page.evaluate(function() {     render $("#foo").text; }) 
You could too thus work foo inward your PhantomJS program, successfully extracting the value from the webpage. Note: render values are express to elementary objects, rather than, say, functions.

IncludeJs too InjectJs
You tin work PhantomJS to inject/include JavaScript files (jQuery too other libraries) inward the electrical current webpage using 2 functions: page.injectJs too page.includeJs.

Difference betwixt injectJs too includeJs
page.injectJs pauses execution until the script is loaded, piece page.includeJs loads the script similar whatever other. page.includeJs includes external script from the specified url (usually a remote location) on the page too executes the callback upon completion. Injects external script code from the specified file into the page (like includeJs, except that the file does non require to live on accessible from the hosted page) too returns truthful if injection is successful, otherwise it returns false.. Note: both convey callbacks.
 page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {  /* jQuery is loaded, forthwith manipulate the DOM */     var foo = page.evaluate(function() {         render $("#foo").text;     });     // create what you lot gotta create alongside 'foo'     // ... }); 
The higher upwardly snippet volition opened upwardly up a spider web page, include the jQuery library into the page too evaluate the statement.
Console.logging from your spider web browser
Well, if you lot type console.log("Hello, World!") inward your PhantomJS program, that volition live on printed to your terminal. If, however, your webpage tries to log the same message, it volition overstep past times unnoticed! So if your webpage prints a bunch of traces to the console, you'll never encounter 'em.
Specifically, the next code does nix because "Hello, World!" is printed inward the context of the browser:
 page.evaluate(function() {     console.log("Hello, World!") }) 
So, what if you lot desire to log messages to your final from within your webpage? The play a joke on is to work the page.onConsoleMessage trial too echo whatever messages printed inward the browser out to your terminal. Try this:
 page.onConsoleMessage = function(msg){     console.log(msg); }; 

waitFor.js
PhantomJS beginners constantly inquire how they tin hold back for something to look on their webpage earlier acting. For example, perchance they desire a banner to look too and thus extract closed to text from it. Say "#foo" is forthwith a div that loads a few seconds afterwards the page has appeared. If you lot only work the next code, you'll larn unexpected results, every bit the banner may non live on loaded at the fourth dimension of query:
 var page = require('webpage').create(); page.open('http://www.sample.com', function() {     var foo = page.evaluate(function() {         render $("#foo").text;     });     // ...     phantom.exit(); }); 
Instead, you lot should work waitFor.js, a prissy JavaScript snippet provided past times the PhantomJS guys. This role is pretty simple, but very, rattling useful. Essentially, it queries the page every few seconds (the exact interval is an optional parameter), executing a user-specified role when a for certain status has been met. Expanding on the previous example, our code mightiness facial expression similar the next (excluding the lengthy Definition of waitFor):
  role waitFor(testFx, onReady, timeOutMillis) {     var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s         start = novel Date().getTime(),         status = false,         interval = setInterval(function() {             if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {                 // If non time-out yet too status non yet fulfilled                 status = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code             } else {                 if(!condition) {                     // If status soundless non fulfilled (timeout but status is 'false')                     console.log("'waitFor()' timeout");                     phantom.exit(1);                 } else {                     // Condition fulfilled (timeout and/or status is 'true')                     console.log("'waitFor()' finished inward " + (new Date().getTime() - start) + "ms.");                     typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to create in i trial the status is fulfilled                     clearInterval(interval); //< Stop this interval                 }             }         }, 250); //< repeat banking concern fit every 250ms };   var page = require('webpage').create(); page.open('http://www.sample.com', function() {     waitFor(function() {             // Check inward the page if a specific chemical component subdivision is forthwith visible             render page.evaluate(function() {                 render $("#foo").is(":visible");             });         }, function() {            var foo = page.evaluate(function() {                 render $("#foo").text;             });             // ...             phantom.exit();         });        }); }); 
Source: http://www.princeton.edu/ crmarsh/phantomjs/
https://github.com/ariya/phantomjs/wiki/API-Reference-WebPage
Sumber http://developer-paradize.blogspot.com

Comments

Popular posts from this blog

What Are The Main Components of a Computer System

Top Qualities To Look For In An IT Support Team

How To Integrate Google Adwords Api Into Codeigniter?