一. phantomjs定義html
無界面的webkit引擎,它爲咱們提供了一個命名行的瀏覽器接口,能夠幫助咱們生成網頁的截圖以及抓取網頁內容。jquery
二. phantomjs 下載及安裝git
#phantomjs --version 1.9.2
三.簡單demogithub
經過Phantomjs運行簡單的hello world demo以下web
console.log('Hello, world!'); phantom.exit();
#phantom hello.js
hello world
經過Phantomjs抓取網頁的列子:瀏覽器
var page = require('webpage').create(); page.open('http://www.baidu.com',function(){ page.render('baidu.png'); phantom.exit(); });
執行以下命令:框架
#phantom page.js
其生成的圖片結果以下: grunt
例子3:loadspeed.js測試
var page = require("webpage").create(), system = require('system'), t, address; if(system.args.length===1) { console.log('usage: loadinspeed.js <some URL>'); phantom.exit(); } t = Date.now(); address = system.args[1]; console.log(address); page.open(address, function(status){ console.log(status); if(status !== 'success'){ console.log('faild to load the address'); }else { t = Date.now() - t; console.log('loading time ' + t +' msec'); } phantom.exit(); });
執行結果以下ui
D:\demo>phantomjs loadspeed.js http://www.baidu.com http://www.baidu.com success loading time 513 msec
經過evaluate()獲取頁面要素:
var page = require('webpage').create(); page.open("http://phantomjs.org/quick-start.html", function(status) { var title = page.evaluate(function() { return document.title; }); console.log('Page title is ' + title); });
運行結果
# hantomjs element.js
the page title is Qucik Start | PhantomJS
四. phantomjs與其餘測試框剪的整合
phantomjs自己不是一個測試框架,所以,須要藉助其餘的測試框剪來進行測試運行:常見的js測試框架已進行運行其列表以下:
Framework | Test Runner |
---|---|
Buster.JS | built-in |
Capybara | Poltergeist, Terminus |
Mocha | Chutzpah, mocha-phantomjs |
FuncUnit | built-in |
Hiro | built-in |
Karma (née Testacular) | built-in |
Jasmine | Chutzpah, grunt-jasmine-runner, guard-jasmine, phantom-jasmine |
JsTestDriver | js-test-driver-phantomjs |
Laika | built-in |
Robot Framework | phantomrobot |
QUnit | built-in, Chutzpah, JS Test Runner, Qlive, QUnited |
tapedeck | built-in |
Testem | built-in |
WebDriver | GhostDriver |
wru | built-in |
YUITest | Grover, phantomjs-yuitest |