PhantomJS快速入門教程

來源:互聯網
上載者:User

標籤:

PhantomJS 是一個基於 WebKit 的伺服器端 JavaScript API。它全面支援web而不需瀏覽器支援,其快速,原生支援各種Web標準: DOM 處理, CSS 選取器, JSON, Canvas, 和 SVG。 PhantomJS 可以用於 頁面自動化 , 網路監測 , 網頁截屏 ,以及 無介面測試 等。

一、安裝

安裝包: http://phantomjs.org/download.html ,包括 Windows ,Mac OS,Linux版本,自行選擇對應 版本下載解壓即可( 為方便使用,可自已為phantomjs設定環境變數 ),其中帶有一個example檔案夾,裡面有很多已經寫好的代碼供使用。本文假設phantomjs已經安裝好並已設定了環境變數。

二、使用Hello, World!

建立一個包含下面兩行指令碼的文字檔:

console.log(‘Hello, world!‘);phantom.exit();

將檔案另存新檔 hello.js ,然後執行它:

phantomjs hello.js

輸出結果為:Hello, world!

第一行將會在終端列印出字串,第二行 phantom.exit 將退出運行。
在該指令碼中調用 phantom.exit 是非常重要的,否則 PhantomJS 將根本不會停止。

指令碼參數 – Script Arguments

Phantomjs如何傳遞參數呢?如下所示 :

phantomjs examples/arguments.js foo bar baz

其中的foo, bar, baz就是要傳遞的參數,如何擷取呢:

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();

它將輸出 :

0: foo1: bar2: baz
頁面載入 – Page Loading

通過建立一個網頁對象,一個網頁可以被載入,分析和渲染。

下面的指令碼將樣本頁面對象最簡單的用法,它載入 example.com 並且將它儲存為一張圖片, example.png

var page = require(‘webpage‘).create();page.open(‘http://example.com‘, function () {    page.render(‘example.png‘);    phantom.exit();});

由於它的這個特性,PhantomJS 可以用來 網頁截屏 ,截取一些內容的快照,比如將網頁、SVG存成圖片,PDF等,這個功能很牛X。

接下來的 loadspeed.js 指令碼載入一個特殊的URL (不要忘了http協議) 並且計量載入該頁面的時間。

var page = require(‘webpage‘).create(),    system = require(‘system‘),    t, address;if (system.args.length === 1) {    console.log(‘Usage: loadspeed.js <some URL>‘);    phantom.exit();}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(‘Loading time ‘ + t + ‘ msec‘);    }    phantom.exit();});

在命令列運行該指令碼:

phantomjs loadspeed.js http://www.google.com

它輸出像下面的東西:

Loading  http://www.google.com  Loading time 719 msec

代碼運算 – Code Evaluation

要想在網頁的上下文中對JavaScript 或 CoffeeScript 進行運算,使用 evaluate() 方法。代碼是在“沙箱”中啟動並執行,它沒有辦法讀取在其所屬頁面上下文之外的任何JavaScript對象和變數。 evaluate() 會返回一個對象,然而它僅限制於簡單的對象並且不能包含方法或閉包。

這有一個樣本來顯示網頁標題:

var page = require(‘webpage‘).create();page.open(url, function (status) {    var title = page.evaluate(function () {        return document.title;    });    console.log(‘Page title is ‘ + title);});

任何來自於網頁並且包括來自 evaluate() 內部代碼的控制台資訊,預設不會顯示的。要重寫這個行為,使用 onConsoleMessage 回呼函數,前一個樣本可以被改寫成:

var page = require(‘webpage‘).create();page.onConsoleMessage = function (msg) {    console.log(‘Page title is ‘ + msg);};page.open(url, function (status) {    page.evaluate(function () {        console.log(document.title);    });});
DOM操作 – DOM Manipulation

由於指令碼好像是一個Web瀏覽器上啟動並執行一樣,標準的DOM指令碼和CSS選取器可以很好的工作。這使得PhantomJS適合支援各種 頁面自動化任務 。

下面的  useragent.js  將讀取 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‘).textContent;        });        console.log(ua);    }    phantom.exit();});

上面樣本同樣提供了一種自訂 user agent 的方法。

使用JQuery及其他類庫:

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()    });});
網路請求及響應 – Network Requests and Responses

將一個頁面從一台遠程伺服器請求一個資源的時候,請求和響應均可以通過 onResourceRequested  和  onResourceReceived  回調方法追蹤到。樣本  netlog.js :

var page = require(‘webpage‘).create();page.onResourceRequested = function (request) {    console.log(‘Request ‘ + JSON.stringify(request, undefined, 4));};page.onResourceReceived = function (response) {    console.log(‘Receive ‘ + JSON.stringify(response, undefined, 4));};page.open(url);

擷取如何把該特性用於HAR 輸出以及基於YSlow的效能分析的更多資訊,請參閱 網路監控頁面 。

 

PhantomJs官網: http://phantomjs.org/

GitHub: https://github.com/ariya/phantomjs/wiki/Quick-Start

Like一下吧

PhantomJS快速入門教程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.