LoginSignup
6
5

DockerでPlaywrightを起動する。

Last updated at Posted at 2023-06-13

PlaywrightでDockerを動かす

JSで作る

ディレクトリ構成
~/develop/docker/playwright_docker$ tree
.
├── Dockerfile
└── script.js

1 directory, 2 files
Dockerfile
# ベースとなるDockerイメージを指定
FROM mcr.microsoft.com/playwright:focal

# ワーキングディレクトリを設定
WORKDIR /app

# 必要なパッケージをインストール
RUN npm init -y
RUN npm install playwright

# スクリプトをコピー
COPY script.js /app/script.js

# コンテナ起動時に実行するコマンドを設定
CMD ["node", "script.js"]

script.js
const { chromium } = require('playwright');

(async () => {
//   const browser = await chromium.launch({headless: false});
  const browser = await chromium.launch({headless: true});
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://www.google.com');
  const title = await page.title();
  console.log(title);
  await browser.close();
})();

イメージ作成
docker build -t my-playwright-app .
実行結果
~/develop/docker/playwright_docker$ docker run my-playwright-app       
Google

TypeScriptで作る

Dockerfile
# ベースとなるDockerイメージを指定
FROM mcr.microsoft.com/playwright:focal

# ワーキングディレクトリを設定
WORKDIR /app

# 必要なパッケージをインストール
RUN npm init -y
RUN npm install playwright typescript ts-node

# スクリプトをコピー
COPY script.ts /app/script.ts

# コンテナ起動時に実行するコマンドを設定
CMD ["npx", "ts-node", "script.ts"]

script.ts
import { chromium } from 'playwright';

(async () => {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://www.google.com');
  const title = await page.title();
  console.log(title);
  await browser.close();
})();

→GUIを表示するのは追加で設定が必要なようだ。

6
5
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
6
5