Node.js
AWS
lambda
cheerio
axios
0

AWS Lambda の Node.js で axios と cheerio で HTML解析(スクレイピング)

あるテストサーバーから OneTimeToken を取得しようとしたら、レスポンスが HTML しかなかったので、AWS Lambda の Node.js で axioscheerio で、HTML解析(スクレイピング)して JSON をレスポンスさせるようにした話。

Node.js ソースコード

app.js
const axios = require('axios');
const cheerio = require('cheerio');
const url = '{TARGET_PAGE}';

exports.lambda_handler = (event, context, callback) => {
    axios(url)
        .then(({ data }) => {
            const content = getContent(data);
            callback(null, {
                statusCode: 200,
                body: JSON.stringify({ content: content })
            });
        })
        .catch(callback);

};

function getContent(html) {
    const $ = cheerio.load(html);
    const content = $('{TARGET_SELECTOR}').text();
    console.log('Content: ', content);
    return content;
}

ね、簡単でしょ?


開発手順
  1. AWS SAM CLI でプロジェクト作成

    $ sam init --runtime nodejs8.10 --name onetimetoken
    
    ディレクトリ構成
    onetimetoken
    ├── hello_world                 <-- Source code for a lambda function
    │   ├── app.js                  <-- Lambda function code
    │   ├── package.json            <-- NodeJS dependencies
    └── template.yaml               <-- SAM template
    
  2. axios と cheerio をインストール

    $ cd onetimetoke/hello_world
    $ npm install --save axios
    $ npm install --save cheerio
    $ cd ..
    
  3. app.js を上記のコードに書き換える

  4. ローカルでサーバーを起動

    $ sam local start-api
    
    2018-07-02 14:14:25 Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
    2018-07-02 14:14:25 You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template
    2018-07-02 14:14:25  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
    
  5. ブラウザ等で http://127.0.0.1:3000/hello を GET で開くとスクレイピング結果の JSON が取得できます。

  6. AWS へデプロイ

    1. AWS S3 BUCKET作成

      aws s3 mb s3://BUCKET_NAME
      
    2. パッケージ (AWS S3 へコードをアップロード)

      sam package \
          --template-file template.yaml \
          --output-template-file packaged.yaml \
          --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME
      
    3. デプロイ (AWS Lambdaへデプロイ)

      sam deploy \
          --template-file packaged.yaml \
          --stack-name onetimetoken \
          --capabilities CAPABILITY_IAM
      

※当初ヘッドレスブラウザで実装してましたが、AWS Lambda では実行できなかったので、HTMLパーサを使うようにしました。

参照