node.js で phantomJSを使用する

node.js から phantomJSを使用するには下記2つの方法がおすすめです。

  • 1.モジュール Nightmare を使う方法(実行経過が見えるのでおすすめです。)
  • 2.モジュール node-horseman を使う方法

● 1.モジュール Nightmare.js を使って phantomJS を操作する

● モジュール nightmare , vo のインストール

npm install nightmare
npm install vo

● テストプログラムを実行する(Googleへアクセスしてタイトルを取得)

・下記コードを `test.js` で保存

var Nightmare = require('nightmare');
var google = new Nightmare()
    .viewport(1000, 1000)
    .useragent("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36")
    .goto('http://google.com')
    .evaluate(function () {
      return {
        title: document.title,
        href : location.href
      };
    })
    .run(function(err, nightmare) {
        if (err) return console.log(err);
        console.log('Done!');
        console.log(nightmare);
    });

・テストコードを実行

node test.js

GoogleホームページのタイトルとURLが表示されればOKです。

● テストプログラムを実行する(niconicoへアクセスしてログインする)

・下記コードを `niconico_login.js` で保存

var Nightmare = require('nightmare');
var vo = require('vo');
vo(function* () {
  var nico_id   = '###メールアドレス###';
  var nico_pass = '###パスワード###';
  var nightmare = Nightmare({ show: true });
  var link = yield nightmare
    .goto('https://account.nicovideo.jp/login')
    .type('input[id="input__mailtel"]', nico_id)
    .type('input[id="input__password"]', nico_pass)
    .click('#login__submit')
    .wait(2000)
    .then(function() {
      console.log('終了しました');
    });
  yield nightmare.end();
  return link;
})(function (err, result) {
  if (err) return console.log(err);
});

・テストコードを実行

node niconico_login.js

ニコニコ動画にログインできればOKです。

● 2.モジュール node-horseman を使って phantomJS を操作する

● モジュール node-horseman のインストール

npm install node-horseman

● テストプログラムを実行する

・下記コードを `test.js` で保存

var Horseman = require('node-horseman');
var horseman = new Horseman();
var filename = 'test.png';
horseman
    .userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
    .open('http://www.google.com')
    .type('input[name="q"]', 'github')
    .click('[name="btnK"]')
    .keyboardEvent('keypress', 16777221)
    .waitForSelector('div.g')
    .count('div.g')
    .log() // prints out the number of results
    .screenshot(filename)
    .log(filename)
    .close();

・テストコードを実行

node test.js

Googleの検索結果の画面が test.png に保存されれば正常に動作しています。

参考 : https://www.sitepoint.com/?p=124173

No.1059
10/03 12:44

edit