1.测试下加载一个网页的速度,从运行开始计时到页面加载完毕。
var page=require('webpage').create(),
system=require('system'),
t,address;
if(system.args.length==1){
console.log("no input");
phantom.exit();
}
t=Date.now();
address=system.args[1];
page.open(address,function(status){
if(status!=='success'){
console.log('load fail');
}else{
t=Date.now()-t;
console.log('loading time'+t+'ms');
}
phantom.exit();
});
2.从网页抓取一些info,拿百度新闻为例子
var page = require('webpage').create();
page.open('http://news.baidu.com/', function (status) { //打开页面
if (status !== 'success') {
console.log('FAIL to load the address');
} else {
console.log(page.evaluate(function () {
var d= ''
var c = document.querySelectorAll('.hdline1 a')
var l = c.length;
for(var i =0;i<l;i++){
d=d+c[i].innerText+'\n'
}
return d
}))
}
phantom.exit();
});
命令行输入打印的文本信息保存到工程目录下的222.txt文本中。
注意!!
网页内部的console语句,以及evaluate方法内部的console语句,默认不会显示在命令行。这时可以采用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();
});