在CentOS7上安装使用PhantomJS(非源码编译)
踩到PhantomJS的坑了,在上文介绍过在CentOS上编译安装PhantomJS,根据官方提供的安装方法,发现一些问题:
使用 git checkout <版本号> 的时候,只有2.1.1版本能生成出build.py文件,而最新的版本是生成不出来的,所以无法使用 2.1.4python build.py命令进行编译,但即便我用2.1.1版本编译的时候不知道是不是因为网络问题一直会卡在一个地方,这个过程的确需要很长的时候,执行脚本的时候程序会提示需要30分钟左右,但是我硬生生等了3个小时它一直卡在某个地方不动.
所以,我打算放弃编译安装,就在我下载使用最新版本的二进制程序的时候使用phantomjs命令却报错
phantomjs: error while loading shared libraries: libssl.so.1.0.0: cannot open shared object file: No such file or directory
Google了一下,在官方Github的issues里面得到了一个回复建议使用旧版的2.1.1:
Try the older 2.1.1 pre-built binary and see if that works for you. For me that works on both Ubuntu and Centos.
于是重新来安装一遍
PhantomJS 2.1.1 在CentOS7中的安装方法
下载程序包
wget https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
解压文件包
tar jxvf phantomjs-2.1.1-linux-x86_64.tar.bz2
设置系统PATH变量,这里需要注意修改为你的目录地址
ln -sf /path/to/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs
检查是否可以运行
phantomjs --version
如果得到版本号2.1.1说明已经安装成功.
用PhantomJS输出第一个"Hello World!"
vi hello.js并输入以下内容
console.log('Hello, world!');
phantom.exit();保存退出后运行
phantomjs hello.js
这时候我们应该可以看到程序输出了"Hello, world!"字样
需要注意的是: 文件末尾的 phantom.exit();非常重要,如果没有这行代码phantom程序不会退出.
页面的加载
任何页面URL都可以被page对象加载,下面这行代码展示了如何使用page对象将http://example.com截图保存成example.png的
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();
});接下来我们新建一个loadspeed.js ,并用它输出加载一个页面URL所需要的时间
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();
});运行脚本
phantomjs loadspeed.js http://www.google.com
执行结果
Loading http://www.google.com Loading time 719 msec
提取Web页面的数据
提取数据我们需要使用evaluate()函数,下面这段代码可以提取页面的title内容
var page = require('webpage').create();
page.open(url, function(status) {
var title = page.evaluate(function() {
return document.title;
});
console.log('Page title is ' + title);
phantom.exit();
});如果页面中包含console信息使用evaluate()是无法获取的,而是使用onConsoleMessage回调,如下面这段代码
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
console.log('Page title is ' + msg);
};
page.open(url, function(status) {
page.evaluate(function() {
console.log(document.title);
});
phantom.exit();
});网络请求和响应
所有的请求和响应对应使用onResourceRequested和onResourceReceived回调,使用方法
var page = require('webpage').create();
page.onResourceRequested = function(request) {
console.log('Request ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function(response) {
console.log('Receive ' + JSON.stringify(response, undefined, 4));
};
page.open(url);