phantomjs介紹

一. phantomjs定義html

    無界面的webkit引擎,它爲咱們提供了一個命名行的瀏覽器接口,能夠幫助咱們生成網頁的截圖以及抓取網頁內容。jquery

二. phantomjs 下載及安裝git

  1. 下載地址:http://phantomjs.org/download.html
  2. 直接解壓安裝而且配置path環境變量,執行以下命令查看配置是否正確。
     #phantomjs --version
       1.9.2

 

三.簡單demogithub

   經過Phantomjs運行簡單的hello world demo以下web

  1. 建立簡單的hello.js文件,其內容以下:
    console.log('Hello, world!');
    phantom.exit();
  2. 在命令行執行以下代碼:
    #phantom hello.js
     hello world

     

 

   經過Phantomjs抓取網頁的列子:瀏覽器

  1. 建立以下page.js文件,內容以下
    var page = require('webpage').create();
      page.open('http://www.baidu.com',function(){
       page.render('baidu.png');
       phantom.exit();
    });

     

  2. 執行以下命令:框架

    #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 PoltergeistTerminus
Mocha Chutzpahmocha-phantomjs
FuncUnit built-in
Hiro built-in
Karma (née Testacular) built-in
Jasmine Chutzpahgrunt-jasmine-runnerguard-jasminephantom-jasmine
JsTestDriver js-test-driver-phantomjs
Laika built-in
Robot Framework phantomrobot
QUnit built-inChutzpahJS Test RunnerQliveQUnited
tapedeck built-in
Testem built-in
WebDriver GhostDriver
wru built-in
YUITest Groverphantomjs-yuitest

 

以上參考http://phantomjs.org

相關文章
相關標籤/搜索