在網上一搜一大堆,我也沒有多深入研究
我也只是會創建page
var page = require('webpage').create();
設置屬性
page.paperSize = {
width: '1000px',
height: '700px',
margin: {
top: '0px',
left: '0px'
}
};
page.open(url, function(status) {
//console.log("Status: " + status);
if(status === "success") {
//console.log(page.content); //輸出頁面內容
//在頁面裏執行函數,並返回結果。
var txt=page.evaluate(function(){
return document.querySelector('body').innerHTML
})
console.log(txt);
}else{
//失敗的輸出
console.log('fail:',url)
}
phantom.exit();
});
這些簡單的
但它是有一些有用的功能
1、system
類似於node 執行命令時輸入的參數
node裏是用process.argv 來接收所有參數。
node XX.js XX 這就是argv的順序。
system用法 :
var system=require('system');
//args 爲 運行的文件和其後的配置
//它不會有phantom 配置參數
var args=system.args;
//console.log(args);
var url=args[1];
phantomjs 執行時可能會有--Xx這些配置,args不會有這些。
xx.js 爲下標0。這個功能可以用來做什麼?
可以用process_child 創建子進程,執行phantoms代碼,傳遞參數用。
2、對ssl 也就是https的加載
對於s的是抓取不到的需要在運行時加上參數:
phantomjs --ignore-ssl-errors=true --ssl-protocol=any phantom_giglio.js
執行時設置url
phantomjs --ignore-ssl-errors=true --ssl-protocol=any phantom_child.js 'url'
最好用雙引號哦。
3、process_child 調用,傳遞加載的url
var spawn = require('child_process').spawn;
var result=url+'\n';
var ls = spawn('phantomjs', ['--ignore-ssl-errors=true','--ssl-protocol=any','phantom_child.js', url]);
ls.stdout.setEncoding('utf8');
//當數據返回量大時會分批傳遞過來
var body='';
ls.stdout.on('data', function(data) {
body+=data;
});
ls.stderr.on('data', function (data) {
//console.error("error ",url, data);
});
// 註冊子進程關閉事件
ls.on('exit', function (code, signal) {
console.log('phantom_child exit code=' + code);
//處理數據
});
基礎就是進程調用phantomjs 指定--參數和 調用js 還有js需要的參數url
js 裏回傳用console.log就可以了。
在關閉事件內判斷body接收的內容,用cheerio創建
用它來處理ajax的詳情頁,對於列表url的抓取用request jddom 都可以。
完整的是把phantom.js寫在模塊,列表裏傳遞url,回調函數內返回過濾的數據。
保存到文件內。