Old Sunset Days

Firebase上でWebスクレイピングのコードを動かす

日付 タグ node.js firebase カテゴリ node.js

目次

ローカル環境で動かしていたスクレイピングコードをFirebaseにデプロイ

ネタは以前にやったosmosisを利用したWebスクレイピングのコード。
( ==> Node.jsでWebスクレイピングを試す )

これをFirebaseでちょっと動かしたいと思ったので試しました。
いまだにHello WorldしかやっていないFirebaseの話の続きでもある。
( ==> FirebaseのCloud FunctionsでHello World )

FirebaseでHelloWorldする時に作ったディレクトへ移動。

$ cd myhelloworld/functions/

今回はosmosisパッケージを使うので先にパッケージインストール。

$ npm install osmosis --save

そして前回のWebスクレイピングのコードを少し書き換えて関数化。
exports.getOgpMetaTagとして定義。
前に作ったHello Worldの入っているindex.jsexports.getOgpMetaTagの追記をしたコードはこのようになった。追記でなくてexports.getOgpMetaTagだけにしても良いのだが、今回は追記にした。

index.js

const functions = require('firebase-functions');
const osmosis = require('osmosis');

// 前に作ったHello Worldのサンプル
exports.helloWorld = functions.https.onRequest((request, response) => {
   functions.logger.info("Hello logs!", {structuredData: true});
   response.send("Hello World!");
});

// Webスクレイピング用の関数
exports.getOgpMetaTag = functions.https.onRequest((req, res) => {
  let responseJson;
  osmosis
  .get(req.query['url'])
  .find('head')
  .set({
    site_name: "meta[property='og:site_name']@content",
    url: "meta[property='og:url']@content",
    title: "meta[property='og:title']@content",
    type: "meta[property='og:type']@content",
    description: "meta[property='og:description']@content",
    image: "meta[property='og:image']@content"
  })
  .data(value => responseJson = JSON.stringify(value))
  .error(err => {
    var errorJson = {'error': err};
    responseJson = JSON.stringify(errorJson);
  })
  .done(() => {
    console.log(responseJson);
    console.log("Web scraping was done");
    res.send(responseJson);
  });

})

結果をJSON形式で返すようにするため、JSON.stringifyを使ってJSON整形したデータを返すようにする。 なお、エラーが出た時も返す値はJSONデータにすることにした。

Firebaseにデプロイしての動作チェック

まずはローカルでチェックする場合は、

$ firebase serve

で動作チェックだが、問題なければFirebaseにデプロイして動作チェック。

$ firebase deploy --only functions

デプロイ時のコンソールログは

✔  functions: Finished running predeploy script.
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
✔  functions: required API cloudbuild.googleapis.com is enabled
✔  functions: required API cloudfunctions.googleapis.com is enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (44.57 KB) for uploading
✔  functions: functions folder uploaded successfully
i  functions: updating Node.js 10 function helloWorld(us-central1)...
i  functions: updating Node.js 10 function getOgpMetaTag(us-central1)...
✔  functions[helloWorld(us-central1)]: Successful update operation.
✔  functions[getOgpMetaTag(us-central1)]: Successful update operation.

✔  Deploy complete!

無事にFirebaseへのDeployが完了。
実際にプロジェクトのコンソールからもFunctionsにgetOgpMetaTagの関数が増えているのが確認できた。

テストだが、クエリパラメータでWebスクレイピングで抽出したい対象のURLを与えてJSONで結果を得るので、ブラウザのURLに

https://[deployされたURL]/getOgpMetaTag?url=https://hugo-de-blog.com/mac-androidter/

のようなURLを与えれば、関数のレスポンスはこのようにJSONで結果が得られる。

なお、存在しないURLをクエリパラメータとして与えた場合はエラー内容を含んだJSONが返ってくる。

以上、駆け足的ではあるが、Firebase上でHello World以外のサンプルも動かすことができた。