LoginSignup
18
13

More than 5 years have passed since last update.

macOS で node.js から Headless Chrome を操作してスクレイピング

Posted at

はじめに

この記事は、macOS で Headless Chrome を試す の続きです。
macOS 上で Chrome をヘッドレスモードで起動するまでは、前の記事を読んでください。

下準備

node.js でスクリプトを書く準備をするため、以下のコマンドを実行します。
なお、node.js はあらかじめインストールされていることを想定しています。

$ mkdir try-headless-chrome && cd try-headless-chrome

$ npm init --yes

chrome-remote-interface をプロジェクトに追加する

プログラムから Headless Chrome を操作するためには、Chrome Debugging Protocol を利用します。これを node.js から使うための chrome-remote-interface を npm を用いてプロジェクトに追加します。

$ npm i -S chrome-remote-interface

発生した通信内容を取得してみる

では、実際にスクリプトを書いて http://qiita.com に含まれる img タグを取得してみます。

index.js
// chrome-remote-interface を読み込む
const CDP = require("chrome-remote-interface");

CDP(client => {
  client.Page
    .enable()
    .then(() => {
      // Qiita にアクセス
      return client.Page.navigate({ url: "http://qiita.com" });
    })
    .then(() => {
      // DOM を取得
      client.DOM.getDocument((error, params) => {
        if (error) {
          console.error(params);
          return;
        }

        // ルート以下の img タグを取得
        const options = {
          nodeId: params.root.nodeId,
          selector: "img"
        };
        client.DOM.querySelectorAll(options, (error, params) => {
          if (error) {
            console.error(params);
            return;
          }

          // 取得した各タグの情報を表示
          params.nodeIds.forEach(nodeId => {
            const options = {
              nodeId: nodeId
            };
            client.DOM.getAttributes(options, (error, params) => {
              if (error) {
                console.error(params);
                return;
              }
              console.log(params.attributes);
            });
          });
        });
      });
    });
}).on("error", err => {
  console.error(err);
});

これを実行すると、以下のような結果が得られるはずです。
なお、これを実行する際には Chrome がヘッドレスモードで起動している必要があります。方法は前回の記事 macOS で Headless Chrome を試す を参考にしてください。

$ node index.js
[ 'class',
  'landingHeader_siteid',
  'src',
  'https://cdn.qiita.com/assets/siteid-large-c5f1d2812cc28cb0621d57061b9eb0f5.png' ]
[ 'class',
  'landingOtherServices_serviceLogo',
  'src',
  'https://cdn.qiita.com/assets/landing-kobito-0868b90bcc1770f0e1c98a513fdc0154.png' ]
[ 'class',
  'landingOtherServices_serviceLogo',
  'src',
  'https://cdn.qiita.com/assets/landing-team-6e3e3b738fc71c1c1d8c838218c8f94f.png' ]

まとめ

node.js から Headless Chrome を操作して任意のタグの情報を抽出するまでをやってみました。ここから先は Chrome Debugging Protocol のリファレンス を参考に試行錯誤していくしかなさそうです。

参考

18
13
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
18
13