phontomjs
phontomjs及其小巧可爱,它通过模拟浏览器行为,帮助你进行爬虫及自动化测试。
下载地址:官网下载地址
下载后解压至任意位置,添加此位置到系统环境中,就可以在命令行中使用啦。
案例1:
将下列代码保存至hello.js中
console.log('Hello, world!');
phantom.exit();
在cmd中,输入命令,phantomjs %yourpath%\hello.js
%yourpath%是你存放hello.js的位置
输出结果:
Hello, world!
console.log()用于输出信息至终端
phantom.exit用来中止并退出终端,如果没有这个语句,终端就会一直运行
web page对象
该对象可以帮助你对网页进行加载和分析,请看如下案例:
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();
});
这是对于webpage对象的一个简单应用,它加载网页并把它作为图片保存至脚本的文件夹。
requre是一个工厂函数,可以得到要用的对象
evaluate()函数--执行javascript
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();
});
该案例使用javascript返回页面的标题
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);
网页在加载时会调用
onResourceRequested = function(request){}
onResourceReceived = function(response){}
可以复写这两个方法来为你服务