官網去下載壓縮包 解壓出來就行 設置bin目錄環(huán)境變量 有個examples文件夾 里邊有大量例子
參考文檔
example1 hello
//新建js文件 hello.js
console.log("hello phantomJS");
phantom exit();
命令行運行 phantomjs hello.js
輸出 hello phantomJS
其中exit是退出phantom 的 否則會一直運行
example2 傳參
運行的時候可以直接傳遞參數(shù) 書寫格式是這樣的
新建arguments.js文件,代碼如下
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();
phantomjs arguments.js foo bar
網頁訪問 截圖 牛逼功能的開始
var page = require('webpage').create();
page.open('http://example.com', function () {
page.render('example.png');
phantom.exit();
});
open訪問網頁 open(url,function(status){
if (status !== 'success') {
console.log('FAIL to load the address');
} else{}
})
render方法 會把網頁 的快照保存
下邊這個例子 傳入一個url 別忘記帶上http協(xié)議 輸出訪問網頁花費了多長時間
var system = require('system'),
page = require('webpage').create(),
address,t;
if (system.args.length === 1) {
console.log('Try to pass some args when invoking this script!');
phantom.exit();
}
address=system.args[1];
t=Date.now(); //獲取當前時間戳
page.open(address,function(status){
if(status!='success'){
console.log('FAIL to load the address');
}else{
t=Date.now()-t;
console.log('Loading time ' + t + ' msec');
}
phantom.exit();
})
evaluate 獲取window下的變量 不能拿到閉包里的東西
一個顯示網頁標題的例子
var page = require('webpage').create();
page.open(url, function (status) {
var title = page.evaluate(function () {
return document.title;
});
console.log('Page title is ' + title);
});
操作dom的開始
下面的 useragent.js 將讀取 id 為qua的元素的 textContent 屬性:
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'SpecialAgent1111111111';
page.open('http://www.httpuseragent.org', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function () {
return document.getElementById('qua').textContent;
});
console.log(ua);
}
phantom.exit();
});
一個使用Juqery庫的例子
var page = require('webpage').create();
page.open('http://www.sample.com', function() {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
$("button").click();
});
phantom.exit()
});
});
終極牛逼技能拔取網頁請求 和收到的響應的數(shù)據(jù)
var page = require('webpage').create(),
system = require('system'),
address;
if (system.args.length === 1) {
console.log('Usage: netlog.js <some URL>');
phantom.exit(1);
} else {
address = system.args[1];
page.onResourceRequested = function (req) {
console.log('requested: ' + JSON.stringify(req, undefined, 4));
};
page.onResourceReceived = function (res) {
console.log('received: ' + JSON.stringify(res, undefined, 4));
};
page.open(address, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
}else{
console.log('over')
}
phantom.exit();
});
}