Linux/centos installation Deployment Phantomjs and use

Source: Internet
Author: User

Phantomjs is a WebKit -based server-side JavaScript API. It fully supports the web without the need for browser support, its fast, native support for various web standards: DOM processing, CSS selectors, JSON, Canvas, and SVG. Phantomjs can be used for page automation, network monitoring, web screen screenshots, and no interface testing, etc.

One. Installation:

Get the installation package and unzip:

#mkdir ~/bin/

#cd ~/bin/

#wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.7-linux-x86_64.tar.bz2

#tar-XJVF phantomjs-1.9.7-linux-x86_64.tar.bz2

Put the executable file into the system path:

#sudo ln-s ~/bin/phantomjs-1.9.7-linux-x86_64/bin/phantomjs/usr/local/bin/phantomjs

Install dependent--fontconfig and FreeType:

#yum Install Fontconfig freetype2

Test the PHANTOMJS under the terminal. You should see the following output:

#phantomjs-V

1.9.7

#cd/root/bin/phantomjs-1.9.7-linux-x86_64/bin

Create a new script and confirm that it is OK:

#vi A.js

1 var page = require (' webpage '). Create (); 2 page.open (' https://www.baidu.com/', function () {3     page.render (' test/ Example.png '); 4     phantom.exit (); 5});

Test after saving

#phantomjs A.js

When finished, a test folder appears, with a picture inside the folder

View picture, display garbled.

solution, install fonts.

#yum Install bitmap-fonts BITMAP-FONTS-CJK

Execute again

#phantomjs A.js

Look at the picture and the font appears normal.

Two. Use:

Hello, world!.

Create a new text file that contains the following two lines of script:

#vi Hello.js

1 Console.log (' Hello, world! '); 2 Phantom.exit ();

Save the file after execution:

#phantomjs Hello.js

The output is: Hello, world!

The first line prints out the string at the terminal, and the second row phantom.exit exits the run.
It is important to call in this script phantom.exit , otherwise PHANTOMJS will not stop at all.

Script Parameters –script Arguments

How do phantomjs pass parameters? As shown below:

1 phantomjs examples/arguments.js foo bar baz

where foo, bar, Baz is the parameter to pass, how to get it:

1 var system = require (' system '); 2 if (system.args.length = = = 1) {3     console.log (' Try to pass some args when invoking T His script! '); 4} else {5     System.args.forEach (function (arg, i) {6             Console.log (i + ': ' + arg); 7     }); 8}9 phantom.exit ();

It will output:

1 0:foo2 1:bar3 2:baz
Page Loading –page Loading

By creating a Web Page object, a Web page can be loaded, parsed, and rendered.

The following script will be the simplest use of the sample Page object, which loads the example.com and saves it as a picture example.png .

#vi A.js

1 var page = require (' webpage '). Create (); 2 page.open (' https://www.baidu.com/', function () {3     page.render (' test/ Example.png '); 4     phantom.exit (); 5});

Test after saving

#phantomjs A.js

Because of this feature, PHANTOMJS can be used to screen screenshots, to intercept some of the content of the snapshot, such as the page, SVG saved into a picture, PDF, etc., this function is very ox x.

The next loadspeed.js script loads a special URL (do not forget the HTTP protocol) and metered the time it takes to load the page.

1 var page = require (' webpage '). Create (), 2     system = require (' System '), 3     T, address; 4  5 if (System.args.leng th = = 1) {6     console.log (' Usage:loadspeed.js <some url> '); 7     phantom.exit (); 8} 9 T = Date.now (); ad Dress = system.args[1];12 Page.open (address, function (status) {     if (status!== ' success ') {         console.log (' FAIL to load the address ');     else {+         t = Date.now ()-t;17         console.log (' Loading time ' + t + ' msec '); 18
   }19     phantom.exit (); 20});

Run the script at the command line: 

1 Phantomjs loadspeed.js http://www.google.com

It outputs something like the following:

1 Loading  http://www.google.com  Loading time 719 msec

Code Operation –code Evaluation

To operate on JavaScript or coffeescript in the context of a Web page, use the evaluate() method. The code runs in the sandbox, and it has no way to read any JavaScript objects and variables that are outside the context of the page to which it belongs. evaluate()returns an object, however it is limited to simple objects and cannot contain methods or closures.

Here's an example to display the page title:

1 var page = require (' webpage '). Create (); 2 page.open (URL, function (status) {3     var title = Page.evaluate (function () { 4         return document.title;5     }); 6     console.log (' Page title is ' + title '); 7});

Any console information that comes from a Web page and includes evaluate() internal code is not displayed by default. To override this behavior, using onConsoleMessage a callback function, the previous example can be rewritten as:

1 var page = require (' webpage '). Create (); 2 page.onconsolemessage = function (msg) {3     console.log (' page title is ' + MS g); 4};5 page.open (URL, function (status) {6     page.evaluate (function () {7         console.log (document.title); 8     } ); 9});
DOM Operation –dom Manipulation

Because the script appears to be running on a Web browser, standard DOM scripts and CSS selectors work well. This makes the PHANTOMJS suitable for supporting a variety of page automation tasks.

The following useragent.js will read the attributes of an element with ID myagent textContent :

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 '). textcontent;10         }); One         Console.log (UA);     }13     phantom.exit (); 14});

The example above also provides a custom user agent method.

Use jquery and other class libraries:

1 var page = require (' webpage '). Create (); 2 page.open (' http://www.sample.com ', function () {3     page.includejs ("http ://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js ", Function () {4         page.evaluate (function () {5             $ ("button"). Click (); 6         }); 7         phantom.exit () 8     }); 9});
Network request and Response –network requests and responses

When a page is requested from a remote server for a resource, both the request and the response can be traced through the onResourceRequested onResourceReceived callback method. Example Netlog.js:

1 var page = require (' webpage '). Create (); 2 page.onresourcerequested = function (Request) {3     console.log (' request ' + J Son.stringify (Request, undefined, 4)); 4};5 page.onresourcereceived = function (response) {6     console.log (' Receive ') + json.stringify (response, Undefined, 4)); 7};8 page.open (URL);

For more information on how to use this feature for HAR output and YSlow-based performance analysis, see the Network Monitoring page.

PHANTOMJS Official website: http://phantomjs.org/

Reprint: http://www.cnblogs.com/10-22/articles/4383196.html

Linux/centos installation Deployment Phantomjs and use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.