最近在使用Python爬取網頁內容時,老是遇到JS臨時加載、動態獲取網頁信息的困難。例如爬取CSDN下載資源評論、搜狐圖片中的「原圖」等,此時嘗試學習Phantomjs和CasperJS來解決這個問題。這第一篇文章固然就是安裝過程及入門介紹。
javascript
下載地址:http://phantomjs.org/
官網介紹:
PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.
Full web stack No browser required.
PhantomJS是一個服務器端的 JavaScript API 的WebKit(開源的瀏覽器引擎)。其支持各類Web標準: DOM 處理, CSS 選擇器, JSON, Canvas 和 SVG。PhantomJS能夠用於頁面自動化,網絡監測,網頁截屏,以及無界面測試等。
下載PhantomJS解壓後以下圖所示:php
console.log('Hello world!'); phantom.exit();經過Ctrl+R打開CMD調用phantomjs.exe執行該程序輸出以下圖所示:
1 var system = require('system'); 2 if (system.args.length === 1) { 3 console.log('Try to pass some args when invoking this script!'); 4 } else { 5 system.args.forEach(function (arg, i) { 6 console.log(i + ': ' + arg); 7 }); 8 } 9 phantom.exit();
var page = require('webpage').create(); page.open('http://www.baidu.com', function () { page.render('example.png'); phantom.exit(); });
1 var page = require('webpage').create(), 2 system = require('system'), 3 t, address; 4 5 if (system.args.length === 1) { 6 console.log('Usage: loadspeed.js <some URL>'); 7 phantom.exit(1); 8 } else { 9 t = Date.now(); 10 address = system.args[1]; 11 page.open(address, function (status) { 12 if (status !== 'success') { 13 console.log('FAIL to load the address'); 14 } else { 15 t = Date.now() - t; 16 console.log('Page title is ' + page.evaluate(function () { 17 return document.title; 18 })); 19 console.log('Loading time ' + t + ' msec'); 20 } 21 phantom.exit(); 22 }); 23 }
運行程序如所示:
4.代碼運算-Code Evaluation
經過在網頁上下文中對JavaScript代碼進行計算,使用evaluate()方法。代碼是在「沙箱(sandboxed)」中運行的,它沒有辦法讀取在其所屬頁面上下文以外的任何JavaScript對象和變量。evaluate()會返回一個對象,然而它僅限制於簡單的對象而且不能包含方法或閉包。
下面這段代碼用於顯示網頁標題:html
1 var page = require('webpage').create(); 2 page.open('http://www.csdn.net', function(status) { 3 var title = page.evaluate(function() { 4 return document.title; 5 }); 6 phantom.outputEncoding="gbk"; 7 console.log('Page title is ' + title); 8 phantom.exit(); 9 });
輸出以下圖所示:java
任何來自於網頁而且包括來自evaluate()內部代碼的控制檯信息,默認不會顯示的。要重寫這個行爲,使用onConsoleMessage回調函數,前一個示例能夠被改寫成:node
var page = require('webpage').create(); phantom.outputEncoding="gbk"; page.onConsoleMessage = function(msg) { console.log('Page title is ' + msg); }; page.open('http://www.csdn.net', function(status) { page.evaluate(function() { console.log(document.title); }); phantom.exit(); });
調用phantomjs gettile2.js便可。
5.DOM操做-DOM Manipulation
由於腳本好像是一個Web瀏覽器上運行的同樣,標準的DOM腳本和CSS選擇器能夠很好的工做。這使得PhantomJS適合支持各類頁面自動化任務。
參考page automation tasks
下面的 useragent.js(examples文件樣本)將讀取id 爲myagent的元素的 textContent 屬性:jquery
1 var page = require('webpage').create(); 2 console.log('The default user agent is ' + page.settings.userAgent); 3 page.settings.userAgent = 'SpecialAgent'; 4 page.open('http://www.httpuseragent.org', function (status) { 5 if (status !== 'success') { 6 console.log('Unable to access network'); 7 } else { 8 var ua = page.evaluate(function () { 9 return document.getElementById('myagent').innerText; 10 }); 11 console.log(ua); 12 } 13 phantom.exit(); 14 });
輸入以下指令,獲取id=myagent元素的值:
phantomjs examples/useragent.jsgit
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() }); });
The above snippet will open up a web page, include the jQuery library into the page, and then click on all buttons using jQuery. It will then exit from the web page. Make sure to put the exit statement within the page.includeJs or else it may exit prematurely before the javascript code is included.
即須要確保JavaScript代碼中包括引用的頁面存在。The Webpage instance具體用法參考前面官方文檔。
6.網絡請求及響應 – Network Requests and Responses
當一個頁面從一臺遠程服務器請求一個資源的時候,請求和響應都可以經過 onResourceRequested 和 onResourceReceived 回調方法追蹤到。文檔示例 netlog.js:github
1 var page = require('webpage').create(), 2 system = require('system'), 3 address; 4 5 if (system.args.length === 1) { 6 console.log('Usage: netlog.js <some URL>'); 7 phantom.exit(1); 8 } else { 9 address = system.args[1]; 10 11 page.onResourceRequested = function (req) { 12 console.log('requested: ' + JSON.stringify(req, undefined, 4)); 13 }; 14 15 page.onResourceReceived = function (res) { 16 console.log('received: ' + JSON.stringify(res, undefined, 4)); 17 }; 18 19 page.open(address, function (status) { 20 if (status !== 'success') { 21 console.log('FAIL to load the address'); 22 } 23 phantom.exit(); 24 }); 25 }
輸入指令:
phantomjs examples/netlog.js http://www.baidu.com
輸出部份內容:web
1 received: { 2 "contentType": "text/javascript; charset=gbk", 3 "headers": [ 4 { 5 "name": "Server", 6 "value": "bfe/1.0.8.5" 7 }, 8 { 9 "name": "Date", 10 "value": "Tue, 18 Aug 2015 20:10:03 GMT" 11 }, 12 { 13 "name": "Content-Type", 14 "value": "text/javascript; charset=gbk" 15 }, 16 { 17 "name": "Content-Length", 18 "value": "88" 19 }, 20 { 21 "name": "Connection", 22 "value": "keep-alive" 23 }, 24 { 25 "name": "Cache-Control", 26 "value": "private" 27 } 28 ], 29 "id": 13, 30 "redirectURL": null, 31 "stage": "end", 32 "status": 200, 33 "statusText": "OK", 34 "time": "2015-08-18T20:09:38.085Z", 35 "url": "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=&json=1&p=3& 36 sid=16486_16222_1421_16896_16738_12825_12868_16800_16659_16424_16514_15936_12073 37 _13932_16866&csor=0&cb=jQuery110208203572703059763_1439928574608&_=1439928574609 38 " 39 }
獲取如何把該特性用於HAR 輸出以及基於YSlow的性能分析的更多信息,請參閱網絡監控頁面:network monitoring
下面顯示了從英國廣播公司網站得到典範的瀑布圖(waterfall diagram):ajax
PS:其餘本分參考官方文檔,目錄以下,examples中包括每一個js對應的用途、github中源代碼、Troubleshooting等。
下載地址:http://casperjs.org/
官方文檔:http://docs.casperjs.org/en/latest/
PS:準備下一篇文章介紹
參考資料:
用CasperJs自動瀏覽頁面-by:kiwi小白 CSDN
PhantomJS安裝及快速入門教程
Windows中Phantomjs + Casperjs安裝使用方法
CasperJS 的安裝和快速入門-oschina
使用 CasperJS 對 Web 網站進行功能測試-oschina
利用nodejs+phantomjs+casperjs採集淘寶商品的價格
[譯]CasperJS,基於PhantomJS的工具包
最後但願文章對你有所幫助吧!若是有不足之處,還請海涵~
(By:Eastmount 2015-8-19 深夜4點半 http://blog.csdn.net/eastmount/)