Phantomjs教程

phantom 笔记

下载

使用 brew 下载: brew install phantomjs

简单的例子

打开一个网页

1
2
3
4
5
6
7
8
var page = require('webpage').create();
page.open('http://example.com', function(status) {
console.log("Status: " + status);
if(status === "success") {
page.render('example.png');
}
phantom.exit();
});

然后在终端输入: phantomjs test.js

显示加载时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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('Loading ' + system.args[1]);
console.log('Loading time ' + t + ' msec');
}
phantom.exit();
});