3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWS LambdaでPlaywrightを動かす

Last updated at Posted at 2024-04-22

今まで https://github.com/JupiterOne/playwright-aws-lambda を使わせてもらっていたのですが、コードを更新すると急に動かなくなってしまい https://github.com/Sparticuz/chromium に乗り換えたので導入メモです。

ほとんどREADMEに記載の通りです。

npm init
npm install --save playwright-core
npm install --save-dev @sparticuz/chromium
  • node_modulesフォルダをzip化
  • 50MBを超えるのでS3にアップ
  • Lambdaのレイヤーを作成
    • 先ほどS3にアップしたzipのURLを指定
    • x86_64とNode.js 18.xを指定
  • Lambdaの関数を作成
    • 先ほど作成したカスタムレイヤーを追加
    • 設定→一般設定からメモリを2000MB程度、タイムアウトを2分程度に増やす
    • コードソースのindex.mjsをindex.jsに変更して中身を書き換え
    • DeployとTestを実行してページタイトルが表示されたら完了
const { chromium: playwright } = require('/opt/node_modules/playwright-core');
const chromium = require('/opt/node_modules/@sparticuz/chromium');

chromium.setHeadlessMode = true;

exports.handler = async (event) => {
  const browser = await playwright.launch({
    args: chromium.args,
    executablePath: await chromium.executablePath(),
    headless: chromium.headless,
  });

  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://example.com');
  const pageTitle = await page.title();
  await browser.close();

  console.log(pageTitle)
}

ちなみに、以前の環境で出ていたエラーログは以下でした。

page.goto: Target page, context or browser has been closed
3
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?