日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

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

 看見就非常 2015-09-18
        最近在使用Python爬取網(wǎng)頁內(nèi)容時,總是遇到JS臨時加載、動態(tài)獲取網(wǎng)頁信息的困難。例如爬取CSDN下載資源評論、搜狐圖片中的“原圖”等,此時嘗試學習Phantomjs和CasperJS來解決這個問題。這第一篇文章當然就是安裝過程及入門介紹。

一. 安裝Phantomjs

        下載地址:http:///
        官網(wǎng)介紹:
          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是一個服務(wù)器端的 JavaScript API 的WebKit(開源的瀏覽器引擎)。其支持各種Web標準: DOM 處理, CSS 選擇器, JSON, Canvas 和 SVG。PhantomJS可以用于頁面自動化,網(wǎng)絡(luò)監(jiān)測,網(wǎng)頁截屏,以及無界面測試等。

        下載PhantomJS解壓后如下圖所示:


        在該文件夾下創(chuàng)建test.js文件,代碼如下:
[javascript] view plaincopy
  1. console.log('Hello world!');  
  2. phantom.exit();  
        通過Ctrl+R打開CMD調(diào)用phantomjs.exe執(zhí)行該程序輸出如下圖所示:


        參考官方文檔:http:///documentation/
        1、腳本參數(shù)-arguments.js
        同時其自帶的examples文件夾中有很多模板代碼,其中獲取腳本參數(shù)代碼如下:

[javascript] view plaincopy
  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();  
        運行程序及輸出結(jié)果如下圖所示:
        phantomjs examples/arguments.js arg0 agr1 arg2 arg3


        2、網(wǎng)頁截圖
        在根目錄新建文件loadpic.js,其代碼如下:
[javascript] view plaincopy
  1. var page = require('webpage').create();  
  2. page.open('http://www.baidu.com'function () {  
  3.     page.render('example.png');  
  4.     phantom.exit();  
  5. });  
        運行程序結(jié)果如下圖所示:
        phantomjs loadpic.js

        短短5行代碼讓我第一次體會到了PhantomJS和調(diào)用腳本函數(shù)的強大,它加載baidu頁面并存儲為一張PNG圖片,這個特性可以廣泛適用于網(wǎng)頁快拍、獲取網(wǎng)頁在線知識等功能。同時也感受到了似乎能夠解決我最初的加載JS問題。

        3、頁面加載-Page Loading
          A web page can be loaded, analyzed, and rendered by creating a web page object.
        通過創(chuàng)建一個網(wǎng)頁對象,一個網(wǎng)頁可以被加載,分析和渲染。examples文件夾中的loadspeed.js腳本加載一個特殊的URL (不要忘了http協(xié)議) 并且計量加載該頁面的時間。
[javascript] view plaincopy
  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獲取網(wǎng)頁標題和t=Date.now()-t計算網(wǎng)頁加載時間。此時輸出如下圖所示,但會存在中文亂碼,如何解決呢?


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



        4.代碼運算-Code Evaluation
        通過在網(wǎng)頁上下文中對JavaScript代碼進行計算,使用evaluate()方法。代碼是在“沙箱(sandboxed)”中運行的,它沒有辦法讀取在其所屬頁面上下文之外的任何JavaScript對象和變量。evaluate()會返回一個對象,然而它僅限制于簡單的對象并且不能包含方法或閉包。
        下面這段代碼用于顯示網(wǎng)頁標題:
[javascript] view plaincopy
  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. });  
        輸出如下圖所示:
        任何來自于網(wǎng)頁并且包括來自evaluate()內(nèi)部代碼的控制臺信息,默認不會顯示的。要重寫這個行為,使用onConsoleMessage回調(diào)函數(shù),前一個示例可以被改寫成:
[javascript] view plaincopy
  1. var page = require('webpage').create();  
  2. phantom.outputEncoding="gbk";  
  3. page.onConsoleMessage = function(msg) {  
  4.   console.log('Page title is ' + msg);  
  5. };  
  6. page.open('http://www.csdn.net'function(status) {  
  7.   page.evaluate(function() {  
  8.     console.log(document.title);  
  9.   });  
  10.   phantom.exit();  
  11. });  
        調(diào)用phantomjs gettile2.js即可。

        5.DOM操作-DOM Manipulation
        因為腳本好像是一個Web瀏覽器上運行的一樣,標準的DOM腳本和CSS選擇器可以很好的工作。這使得PhantomJS適合支持各種頁面自動化任務(wù)。
        參考page automation tasks
        下面的 useragent.js(examples文件樣本)將讀取id 為myagent的元素的 textContent 屬性:
[javascript] view plaincopy
  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.'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.js

         上面示例也提供了一種自定義user agent的方法。
         使用JQuery及其他類庫(Use jQuery and Other Libraries)。如果版本是1.6,你也可以把jQuery放入你的頁面中,使用page.includeJs如下:
[javascript] view plaincopy
  1. var page = require('webpage').create();  
  2. page.open('http://www.'function() {  
  3.   page.includeJs("http://ajax./ajax/libs/jquery/1.6.1/jquery.min.js"function() {  
  4.     page.evaluate(function() {  
  5.       $("button").click();  
  6.     });  
  7.     phantom.exit()  
  8.   });  
  9. });  
          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.網(wǎng)絡(luò)請求及響應(yīng) – Network Requests and Responses
        當一個頁面從一臺遠程服務(wù)器請求一個資源的時候,請求和響應(yīng)均可以通過 onResourceRequested 和 onResourceReceived 回調(diào)方法追蹤到。文檔示例 netlog.js:
[javascript] view plaincopy
  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
       
輸出部分內(nèi)容:
  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的性能分析的更多信息,請參閱網(wǎng)絡(luò)監(jiān)控頁面:network monitoring
        下面顯示了從英國廣播公司網(wǎng)站獲得典范的瀑布圖(waterfall diagram):
        
        PS:其他本分參考官方文檔,目錄如下,examples中包括每個js對應(yīng)的用途、github中源代碼、Troubleshooting等。

二. 安裝CasperJS

        下載地址:http:///
        官方文檔:http://docs./en/latest/
        PS:準備下一篇文章介紹

參考資料:
        用CasperJs自動瀏覽頁面-by:kiwi小白 CSDN
        PhantomJS安裝及快速入門教程
        Windows中Phantomjs + Casperjs安裝使用方法
        CasperJS 的安裝和快速入門-oschina
        使用 CasperJS 對 Web 網(wǎng)站進行功能測試-oschina
        利用nodejs+phantomjs+casperjs采集淘寶商品的價格
        [譯]CasperJS,基于PhantomJS的工具包

        最后希望文章對你有所幫助吧!如果有不足之處,還請海涵~
      (By:Eastmount 2015-8-19 深夜4點半   http://blog.csdn.net/eastmount/

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多