[Python爬蟲] 在Windows下安裝PhantomJS和CasperJS及入門介紹(上)

        最近在使用Python爬取網頁內容時,老是遇到JS臨時加載、動態獲取網頁信息的困難。例如爬取CSDN下載資源評論、搜狐圖片中的「原圖」等,此時嘗試學習Phantomjs和CasperJS來解決這個問題。這第一篇文章固然就是安裝過程及入門介紹。

javascript

一. 安裝Phantomjs

         下載地址: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


        在該文件夾下建立test.js文件,代碼以下:
console.log('Hello world!');
phantom.exit();
        經過Ctrl+R打開CMD調用phantomjs.exe執行該程序輸出以下圖所示:


        參考官方文檔: http://phantomjs.org/documentation/
        一、腳本參數-arguments.js
        同時其自帶的examples文件夾中有不少模板代碼,其中獲取腳本參數代碼以下:
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();
        運行程序及輸出結果以下圖所示:
        phantomjs examples/arguments.js arg0 agr1 arg2 arg3
 
        二、網頁截圖
        在根目錄新建文件loadpic.js,其代碼以下:
var page = require('webpage').create();
page.open('http://www.baidu.com', function () {
    page.render('example.png');
    phantom.exit();
});
        運行程序結果以下圖所示:
        phantomjs loadpic.js

        短短5行代碼讓我第一次體會到了PhantomJS和調用腳本函數的強大,它加載baidu頁面並存儲爲一張PNG圖片,這個特性能夠普遍適用於網頁快拍、獲取網頁在線知識等功能。同時也感覺到了彷佛可以解決我最初的加載JS問題。
 
        三、頁面加載-Page Loading
          A web page can be loaded, analyzed, and rendered by creating a web page object.
        經過建立一個網頁對象,一個網頁能夠被加載,分析和渲染。examples文件夾中的loadspeed.js腳本加載一個特殊的URL (不要忘了http協議) 而且計量加載該頁面的時間。
 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 }

 

        運行程序如所示:
        phantomjs examples/loadspeed.js http://www.baidu.com
        其中包括document.title獲取網頁標題和t=Date.now()-t計算網頁加載時間。此時輸出以下圖所示,但會存在中文亂碼,如何解決呢?

        添加以下代碼便可:
        t = Date.now();
        address = system.args[1];
        phantom.outputEncoding="gbk";


        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


         上面示例也提供了一種自定義user agent的方法。
         使用JQuery及其餘類庫(Use jQuery and Other Libraries)。若是版本是1.6,你也能夠把jQuery放入你的頁面中,使用page.includeJs以下:
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等。

 

二. 安裝CasperJS

        下載地址: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/

相關文章
相關標籤/搜索