LoginSignup
5
10

More than 5 years have passed since last update.

gulpでサクッとPhantomJSを実行する

Posted at

はじめに

仕事でPhantomJSを使ってWebアプリのスクリーンショットを自動取得する必要があったので、gulp(実際はさらにjenkinsと組み合わせる予定)からPhantomJSを実行するコードを書いてみました。

サンプル

gulpfile.js
var gulp = require("gulp");
var phantomjs = require('phantomjs-prebuilt');

gulp.task("phantomjs", function(done) {
  var program = phantomjs.exec('phantomjs-script.js');
  program.stdout.pipe(process.stdout);
  program.stderr.pipe(process.stderr);
  program.on('exit', code => {
    done();
  });
});
phantomjs-script.js
var page = require('webpage').create();

//指定したURLを開く
page.open('https://google.com', function(status) {
  console.log("Status: " + status);
  if(status === "success") {
    //screen capture
    page.render('google.png');
  }
  phantom.exit();
});

実行結果

$ gulp phantomjs
[23:19:21] Using gulpfile ~\Documents\node\node-v6.10.0-win-x64\gulpfile.js
[23:19:21] Starting 'phantomjs'...
Status: success
[23:19:25] Finished 'phantomjs' after 4.12 s

カレントディレクトリにgoogle.pngができていました。
google.png

5
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
10