一、安装
安装包下载地址:http://phantomjs.org/download.html,包括Windows,Mac OS,Linux版本,自行选择对应 版本下载解压即可(为方便使用,可自已为phantomjs设置环境变量),其中带有一个example文件夹,里面有很多已经写好的代码供使用。本文假设phantomjs已经安装好并已设置了环境变量。
二、使用
Hello, World!
新建一个包含下面两行脚本的文本文件:
|
1
2
|
console.log(\'Hello, world!\');
phantom.exit(); |
将文件另存为hello.js,然后执行它:
|
1
|
phantomjs hello.js |
输出结果为:Hello, world!
第一行将会在终端打印出字符串,第二行phantom.exit将退出运行。
在该脚本中调用phantom.exit是非常重要的,否则 PhantomJS 将根本不会停止。
脚本参数 – Script Arguments
Phantomjs如何传递参数呢?如下所示 :
|
1
|
phantomjs examples/arguments.js foo bar baz |
其中的foo, bar, baz就是要传递的参数,如何获取呢:
|
1
2
3
4
5
6
7
8
9
|
var system = require(\'system\');
if (system.args.length === 1) {
console.log(\'Try to pass some args when invoking this script!\');
} else {
system.args.forEach(function (arg, i) {
console.log(i + \': \' + arg);
});
}phantom.exit(); |
它将输出 :
0: foo 1: bar 2: baz
页面加载 – Page Loading
通过创建一个网页对象,一个网页可以被加载,分析和渲染。
下面的脚本将示例页面对象最简单的用法,它加载 example.com 并且将它保存为一张图片,example.png。
|
1
2
3
4
5
|
var page = require(\'webpage\').create();
page.render(\'example.png\');
phantom.exit();
}); |
由于它的这个特性,PhantomJS 网页截屏,截取一些内容的快照,比如将网页、SVG存成图片,PDF等,这个功能很牛X。
接下来的loadspeed.js脚本加载一个特殊的URL (不要忘了http协议) 并且计量加载该页面的时间。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
var page = require(\'webpage\').create(),
system = require(\'system\'),
t, address;
if (system.args.length === 1) {
console.log(\'Usage: loadspeed.js <some URL>\');
phantom.exit();
}t = Date.now();address = system.args[1];page.open(address, function (status) {
if (status !== \'success\') {
console.log(\'FAIL to load the address\');
} else {
t = Date.now() - t;
console.log(\'<a title="Loading" href="http://www.woiweb.net/tag/loading">Loading</a> time \' + t + \' msec\');
}
phantom.exit();
}); |