[Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上)
一. 安裝Phantomjs
? ? ? ? 下載地址:http://phantomjs.org/
? ? ? ? 官網(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是一個(gè)服務(wù)器端的 JavaScript API 的WebKit(開(kāi)源的瀏覽器引擎)。其支持各種Web標(biāo)準(zhǔn): DOM 處理, CSS 選擇器, JSON, Canvas 和 SVG。PhantomJS可以用于頁(yè)面自動(dòng)化,網(wǎng)絡(luò)監(jiān)測(cè),網(wǎng)頁(yè)截屏,以及無(wú)界面測(cè)試等。
? ? ? ? 下載PhantomJS解壓后如下圖所示:
? ? ? ? 在該文件夾下創(chuàng)建test.js文件,代碼如下:
console.log('Hello world!'); phantom.exit();? ? ? ? 通過(guò)Ctrl+R打開(kāi)CMD調(diào)用phantomjs.exe執(zhí)行該程序輸出如下圖所示:
? ? ? ??參考官方文檔:http://phantomjs.org/documentation/
? ? ? ? 1、腳本參數(shù)-arguments.js
? ? ? ? 同時(shí)其自帶的examples文件夾中有很多模板代碼,其中獲取腳本參數(shù)代碼如下:
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();? ? ? ? 運(yùn)行程序及輸出結(jié)果如下圖所示:
? ? ? ? phantomjs examples/arguments.js arg0 agr1 arg2 arg3
? ? ? ? 2、網(wǎng)頁(yè)截圖 ? ? ? ? 在根目錄新建文件loadpic.js,其代碼如下:
var page = require('webpage').create(); page.open('http://www.baidu.com', function () {page.render('example.png');phantom.exit(); });? ? ? ? 運(yùn)行程序結(jié)果如下圖所示:
? ? ? ??phantomjs?loadpic.js
? ? ? ? 短短5行代碼讓我第一次體會(huì)到了PhantomJS和調(diào)用腳本函數(shù)的強(qiáng)大,它加載baidu頁(yè)面并存儲(chǔ)為一張PNG圖片,這個(gè)特性可以廣泛適用于網(wǎng)頁(yè)快拍、獲取網(wǎng)頁(yè)在線知識(shí)等功能。同時(shí)也感受到了似乎能夠解決我最初的加載JS問(wèn)題。
? ? ? ??3、頁(yè)面加載-Page Loading
? ? ? ? ??A web page can be loaded, analyzed, and rendered by creating a web page object.
? ? ? ??通過(guò)創(chuàng)建一個(gè)網(wǎng)頁(yè)對(duì)象,一個(gè)網(wǎng)頁(yè)可以被加載,分析和渲染。examples文件夾中的loadspeed.js腳本加載一個(gè)特殊的URL (不要忘了http協(xié)議) 并且計(jì)量加載該頁(yè)面的時(shí)間。
var page = require('webpage').create(),system = require('system'),t, address;if (system.args.length === 1) {console.log('Usage: loadspeed.js <some URL>');phantom.exit(1); } else {t = Date.now();address = system.args[1];page.open(address, function (status) {if (status !== 'success') {console.log('FAIL to load the address');} else {t = Date.now() - t;console.log('Page title is ' + page.evaluate(function () {return document.title;}));console.log('Loading time ' + t + ' msec');}phantom.exit();}); }? ? ? ? 運(yùn)行程序如所示:
? ? ? ? phantomjs examples/loadspeed.js http://www.baidu.com
? ? ? ? 其中包括document.title獲取網(wǎng)頁(yè)標(biāo)題和t=Date.now()-t計(jì)算網(wǎng)頁(yè)加載時(shí)間。此時(shí)輸出如下圖所示,但會(huì)存在中文亂碼,如何解決呢?
? ? ? ? 添加如下代碼即可: ? ? ? ? t = Date.now();
? ? ? ? address = system.args[1];
? ? ? ? phantom.outputEncoding="gbk";
? ? ? ? 4.代碼運(yùn)算-Code Evaluation
? ? ? ? 通過(guò)在網(wǎng)頁(yè)上下文中對(duì)JavaScript代碼進(jìn)行計(jì)算,使用evaluate()方法。代碼是在“沙箱(sandboxed)”中運(yùn)行的,它沒(méi)有辦法讀取在其所屬頁(yè)面上下文之外的任何JavaScript對(duì)象和變量。evaluate()會(huì)返回一個(gè)對(duì)象,然而它僅限制于簡(jiǎn)單的對(duì)象并且不能包含方法或閉包。
? ? ? ? 下面這段代碼用于顯示網(wǎng)頁(yè)標(biāo)題:
var page = require('webpage').create(); page.open('http://www.csdn.net', function(status) {var title = page.evaluate(function() {return document.title;});phantom.outputEncoding="gbk";console.log('Page title is ' + title);phantom.exit(); }); ? ? ? ? 輸出如下圖所示:
? ? ? ? 任何來(lái)自于網(wǎng)頁(yè)并且包括來(lái)自evaluate()內(nèi)部代碼的控制臺(tái)信息,默認(rèn)不會(huì)顯示的。要重寫這個(gè)行為,使用onConsoleMessage回調(diào)函數(shù),前一個(gè)示例可以被改寫成:
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(); }); ? ? ? ? 調(diào)用phantomjs?gettile2.js即可。
? ? ? ? 5.DOM操作-DOM Manipulation
? ? ? ? 因?yàn)槟_本好像是一個(gè)Web瀏覽器上運(yùn)行的一樣,標(biāo)準(zhǔn)的DOM腳本和CSS選擇器可以很好的工作。這使得PhantomJS適合支持各種頁(yè)面自動(dòng)化任務(wù)。
? ? ? ? 參考page automation tasks
? ? ? ??下面的 useragent.js(examples文件樣本)將讀取id 為myagent的元素的 textContent 屬性:
var page = require('webpage').create(); console.log('The default user agent is ' + page.settings.userAgent); page.settings.userAgent = 'SpecialAgent'; 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('myagent').innerText;});console.log(ua);}phantom.exit(); }); ? ? ? ? 輸入如下指令,獲取id=myagent元素的值:
? ? ? ??phantomjs examples/useragent.js
? ? ? ? ?上面示例也提供了一種自定義user agent的方法。
? ? ? ? ?使用JQuery及其他類庫(kù)(Use jQuery and Other Libraries)。如果版本是1.6,你也可以把jQuery放入你的頁(yè)面中,使用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代碼中包括引用的頁(yè)面存在。The Webpage instance具體用法參考前面官方文檔。
? ? ? ? 6.網(wǎng)絡(luò)請(qǐng)求及響應(yīng) – Network Requests and Responses
? ? ? ? 當(dāng)一個(gè)頁(yè)面從一臺(tái)遠(yuǎn)程服務(wù)器請(qǐng)求一個(gè)資源的時(shí)候,請(qǐng)求和響應(yīng)均可以通過(guò) onResourceRequested 和 onResourceReceived 回調(diào)方法追蹤到。文檔示例 netlog.js:
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');}phantom.exit();}); } ? ? ? ? 輸入指令:
? ? ? ? phantomjs examples/netlog.js http://www.baidu.com
? ? ? ? 輸出部分內(nèi)容:
received: {"contentType": "text/javascript; charset=gbk","headers": [{"name": "Server","value": "bfe/1.0.8.5"},{"name": "Date","value": "Tue, 18 Aug 2015 20:10:03 GMT"},{"name": "Content-Type","value": "text/javascript; charset=gbk"},{"name": "Content-Length","value": "88"},{"name": "Connection","value": "keep-alive"},{"name": "Cache-Control","value": "private"}],"id": 13,"redirectURL": null,"stage": "end","status": 200,"statusText": "OK","time": "2015-08-18T20:09:38.085Z","url": "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=&json=1&p=3& sid=16486_16222_1421_16896_16738_12825_12868_16800_16659_16424_16514_15936_12073 _13932_16866&csor=0&cb=jQuery110208203572703059763_1439928574608&_=1439928574609 " } ? ? ? ? 獲取如何把該特性用于HAR 輸出以及基于YSlow的性能分析的更多信息,請(qǐng)參閱網(wǎng)絡(luò)監(jiān)控頁(yè)面:network monitoring
? ? ? ??下面顯示了從英國(guó)廣播公司網(wǎng)站獲得典范的瀑布圖(waterfall diagram):
? ? ? ??
? ? ? ? PS:其他本分參考官方文檔,目錄如下,examples中包括每個(gè)js對(duì)應(yīng)的用途、github中源代碼、Troubleshooting等。
二. 安裝CasperJS
? ? ? ? 下載地址:http://casperjs.org/
? ? ? ? 官方文檔:http://docs.casperjs.org/en/latest/
? ? ? ? PS:準(zhǔn)備下一篇文章介紹
? ? ? ? 用CasperJs自動(dòng)瀏覽頁(yè)面-by:kiwi小白 CSDN
? ? ? ? PhantomJS安裝及快速入門教程
? ? ? ? Windows中Phantomjs + Casperjs安裝使用方法
? ? ? ? CasperJS 的安裝和快速入門-oschina
? ? ? ??使用 CasperJS 對(duì) Web 網(wǎng)站進(jìn)行功能測(cè)試-oschina
? ? ? ? 利用nodejs+phantomjs+casperjs采集淘寶商品的價(jià)格
? ? ? ? [譯]CasperJS,基于PhantomJS的工具包
? ? ? ??最后希望文章對(duì)你有所幫助吧!如果有不足之處,還請(qǐng)海涵~
? ? ? (By:Eastmount 2015-8-19 深夜4點(diǎn)半? ?http://blog.csdn.net/eastmount/)
總結(jié)
以上是生活随笔為你收集整理的[Python爬虫] 在Windows下安装PhantomJS和CasperJS及入门介绍(上)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 生活杂谈:从Z149到Z78随笔
- 下一篇: [Python爬虫] 在Windows下