yuw27b’s blog

技術メモと雑記

GCP Cloud FunctionsでPuppeteerを使う

1日1回スクレイピングしてきてSlackに流してほしい、みたいな簡単なやつなので、Firebaseまではいらない。

Cloud FunctionでランタイムにNode.jsを選択→package.jsonとindex.jsを登録しておき、Cloud Scheduler->Pub/Sub経由で呼び出せばOK。

プチハマりどころ
  • Puppeteerのバージョンが新しすぎると動かない→2020年1月現在ではv2.0.0なら動く。Node.jsのバージョンが10系なので仕方ないのかも。
  • Puppeteer起動時のオプションで、--single-processとか--no-sandboxとかを有効にしておかないと動かない。

最終的にこうなった:

  const browser = await puppeteer.launch({
    headless: true,
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '-–disable-dev-shm-usage',
      '--disable-gpu',
      '--no-first-run',
      '--no-zygote',
      '--single-process',
    ],
  });
  • メモリ1GB割り当てておかないと足りなかった。(処理内容によっては512MBでもなんとかなるかもしれない。または、たまになら失敗しても構わないケースとか。)

console.log()でGCPのログに吐き出せるし、1日1回くらいの頻度であれば無料枠におさまってくれた。
データの永続化も、小さいデータならFirestoreに読み書きで十分という印象。
同じプロジェクト内ならデフォルトでアクセス権もあるので、こんな感じ:

  const firestore = new Firestore({
    projectId: '(PROJECT_ID)'
  });
  const document = firestore.doc('path/to/doc');
  const currentDoc = await document.get(doc => {
    return doc;
  });

/////(なんか処理とか)

  await document.update({
    'xxx': 'yyy'
  });