LoginSignup
1
0

More than 3 years have passed since last update.

Node.js上でCUIコマンドを用いたURLスクレイピング

Last updated at Posted at 2019-08-29

Node.jsを用いたURLスクレイピング

はじめに

Node.jsを用いたスクレイピングは、
記事を漁るとしばしば見受けられます。
Webサーバを立ててリクエスト送るという記事は多いです。
それって、Node.jsの特徴をあまり活かせてないのでは?
と思い立ったためこの記事を書きました。

Node.jsでスクレイピング

JSをサーバサイドでも動作させることができるプラットフォームですが、
JS単体では扱えなかった、CUIコマンドも扱えます。

Webサーバ立てる必要なくない?

Curlコマンド利用してHTTPリクエスト生やして、
HTMLオブジェクトを取得した上でスクレイピングしたほうがよくない?

ということで

Node.js上でCUIコマンドを利用するためには、
child_processモジュール内のexecSync関数を利用します。

余談ですが...
child_processモジュール内のexecSync関数は同期関数
child_processモジュール内のexec関数は非同期関数 なので注意。

CUIExec(argv)関数では引数にURLを指定することで、
該当URLの飛び先にある、HTMLオブジェクトを取得し、
文字列として戻り値に設定します。

index.js
const execSync = require('child_process').execSync;
const CUIExec = (argv) => { // URL
    console.log(argv);
    return execSync("curl " + argv).toString();
}

HTMLオブジェクトを取得したのちに、
正規表現によってhrefタグに紐づけられているURLのみを抽出し、
配列に格納します。

index.js
const urlParserIncludeHTML = (htmlString) => {
    return (htmlString+"").match(/href=\"(.*?)\".*?/gi);
}

if (process.argv[2]) { //コマンドライン引数の取得
    let arrayIncludeURL = [];
    let uriList = [];

    uriList = urlParserIncludeHTML(CUIExec(process.argv[2])).slice();
    console.log(uriList);

    for (let key in uriList) {
        let tmpStr = (uriList[key]+"").replace(/^href="/, "").replace('"', "");
        //任意のファイル拡張子
        if (tmpStr.match(".css") || tmpStr.match(".xml")
            || tmpStr.match(".png") || tmpStr.match(".jpg")
            || tmpStr.match(".svg") || tmpStr.match(".ico")
            || tmpStr.match(".json")) {
            continue;
        } else {
            if (tmpStr.indexOf("http") || tmpStr.indexOf("https")){
                arrayIncludeURL.push(process.argv[2] + tmpStr);
            } else {
                arrayIncludeURL.push(tmpStr);
            }
        }
    }
    console.log(arrayIncludeURL);
}

実行コマンドは以下の通りです。

$ node index.js <URL>

index.jsをchild_processモジュールを利用し、
他のJSファイル上で実行することによって、
他言語との有意差はおいておいても、
JSのみでもソフトウェアの作成が可能です。

1
0
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
1
0