< Back

ラズベリーパイでPlaywrightを使い検索のスクリーンショットを取りまくった話

ラズベリーパイだとPlayWrite対応してなさそうだったけど色々やったら動いた

やり方

chromiumのインストール

$ sudo apt install chromium
$ which chromium
/usr/bin/chromium

後でNode.jsのコードにいれます。

Node.js側コード

{
  "name": "piapp",
  "version": "1.0.0",
  "description": "ラズベリーパイに利用するアプリケーション",
  "main": "index.js",
  "scripts": {
    "start": "NODE_ENV=production forever start -vc ts-node src/index.ts",
    "stop": "NODE_ENV=production forever stop -vc ts-node src/index.ts",
    "dev": "nodemon"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "chrome-aws-lambda": "^10.1.0",
    "node-cron": "^3.0.3",
    "playwright-core": "^1.40.1"
  },
  "devDependencies": {
    "@types/node": "^20.10.4",
    "@types/node-cron": "^3.0.11"
  }
}

この記事が一番参考になった

const piChrome = '/usr/bin/chromium'; // for Raspberry Pi, after like `$ sudo apt install chromium`
import path from 'path';
import fs from 'fs';
import { chromium, devices, Page } from 'playwright-core';
import { nowSecondString } from './utils';

/** TypeのKeyをStringのUnion型にする */
export type NoStringIndex<T> = { [K in keyof T as string extends K ? never : K]: T[K] };
export type DeviceType = keyof NoStringIndex<typeof devices>;
export type DeviceDescriptor = (typeof devices)['Pixel 5'];

export const playwrightScreenshotOnlyLocal = async (page: Page, text?: string) => {
  if (process.env.NODE_ENV === 'production') return;
  await page.screenshot({
    path: path.resolve(__dirname, `../downloads/${nowSecondString()}.jpg`),
    fullPage: false,
  }).catch(_ => undefined);
};

export const googleCheck = async () => {
  const browser = await createChromeBrowser();

  const page = await browser.newPage();
  await page.goto('https://www.google.com/search?q=新宿の天気');
  console.log('await page.title(): ', await page.title());

  await playwrightScreenshotOnlyLocal(page)

  return await browser.close();
};

const defaultOption = {
  headless: true,
  slowMo: 333,
  timeout: 150000, // 120 sec
  args: [
    '--lang=ja', // 日本語対応
  ],
};

export const createChromeBrowser = async () => {
  let executablePath: string | undefined;
  executablePath = fs.existsSync(piChrome) ? piChrome : undefined;
  if (executablePath) return chromium.launch({ executablePath, ...defaultOption });
  return chromium.launch(defaultOption);
};

だいたいこんな感じのコードで動きました。

MacOSで開発しているときは /usr/bin/chromium にchromiumがなく npx install playwrite でインストールした実体を動かして、ラズベリーパイのときは /usr/bin/chromium で動かしました。

これで毎日朝7時に新宿区の天気をスクショして保存するという動作を node-cron で走らせられるようになりました。
20231216_2226794.jpg