LoginSignup
4
3

More than 5 years have passed since last update.

jsonでスクレイピングできるnode_module作りました

Last updated at Posted at 2016-12-24

Nightmare

いまいち、Nightmareがスクレイピングに向かない部分があり、jsonでスクレイピングできるようになるnode_module、The Foolを作りました。

npm install the-fool

Nightmareって、すごいシンプルなAPIになってるんですけど、
やっぱりテスト用のツールなので、メソッドチェーンでシーケンシャルにテストするために作られてるんですよね。

公式から抜粋ですが、phantomだと20行かかっていたものが、4行になりました。

Phantom(20行)

phantom.create(function (ph) {
  ph.createPage(function (page) {
    page.open('http://yahoo.com', function (status) {
      page.evaluate(function () {
        var el =
          document.querySelector('input[title="Search"]');
        el.value = 'github nightmare';
      }, function (result) {
        page.evaluate(function () {
          var el = document.querySelector('.searchsubmit');
          var event = document.createEvent('MouseEvent');
          event.initEvent('click', true, false);
          el.dispatchEvent(event);
        }, function (result) {
          ph.exit();
        });
      });
    });
  });
});

Nightmare(4行)

yield Nightmare()
  .goto('http://yahoo.com')
  .type('input[title="Search"]', 'github nightmare')
  .click('.searchsubmit');

もっと自由にスクレイピングしたい

メソッドチェーンだと、欠点として、プログラマブルに内容を変えるのに苦労しますね。
しかもnightmareの中身は、メソッドによって自身を返したりPromiseのように見える何かを返していたりと、
メソッドチェーンを途中で区切ってごにょごにょしてから何かする、というような自由度が少ないんですね。

何が言いたいのかというと、ぶっちゃけテストじゃなくてスクレイピングしたいんですよ世の名の大半の人達は。

The Fool(実行は1行)

const data = {
  data: [
    ["goto", "https://www.google.co.jp/"],
    ["type", "input[title='Search']", "github nightmare"],
    ["click", ".searchsubmit"]
  ]
};

const fool = new Fool();

yield fool.travel(data);

これで順番を組み替えたり取得してきたデータから処理を変えたり自由自在ですね。

その他

連続してデータをとりたい場合は、coやvoを使いましょう。
wrapができるcoのほうが僅かにおすすめです。

the-foolの中にexample用意しました。
そこでco使って直列なスクレイピングをしています。

注意

使用は自己責任でお願いします!

4
3
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
4
3