LoginSignup
3
2

More than 1 year has passed since last update.

Denoでpuppeteerを使う (windows)

Last updated at Posted at 2021-05-12

puppeteerはNode.js向けのブラウザ自動操作ライブラリですが、Denoからも使用することができます。

deno-puppeteer

作者はDenoメンテナの一人であるLuca Casonato氏です。

使い方

環境はWindows10でやっていきます。
実行方法はReadMeページに書いてある通りです。

import puppeteer from "https://deno.land/x/puppeteer@9.0.0/mod.ts";

ただし、このまま実行するとエラーが出る可能性があります。私は出ました。

error: Uncaught (in promise) Error: Could not find browser revision 869685. Run "PUPPETEER_PRODUCT=chrome deno run -A --unstable https://deno.land/x/puppeteer@9.0.0/install.ts" to download a supported browser binary.
      if (missingText) throw new Error(missingText);
                             ^
    at ChromeLauncher.launch (https://deno.land/x/puppeteer@9.0.0/src/deno/Launcher.ts:99:30)

このエラーが出た場合は以下の手順を実行する必要があります。と書いてあります。

  1. 環境変数PUPPETEER_PRODUCTを設定

    windowsの設定(もしくはコマンドライン)から環境変数PUPPETEER_PRODUCTchromeに設定します。

  2. 初期インストールスクリプトを実行

    deno run -A --unstable https://deno.land/x/puppeteer@<バージョン番号>/install.tsをコマンドラインで実行します。

    C:\Users\...>deno run -A --unstable https://deno.land/x/puppeteer@9.0.0/install.ts
    Download https://deno.land/x/puppeteer@9.0.0/install.ts
    Download https://deno.land/x/progress@v1.1.4/mod.ts
    Download https://deno.land/std@0.74.0/fmt/colors.ts
    Check https://deno.land/x/puppeteer@9.0.0/install.ts
    100.00%                                                    62.7s 174152394/174152394
    Downloaded chrome 869685 to C:\Users\...\AppData\Local\deno\deno_puppeteer\chromium\win64-869685\chrome-win\chrome.exe from https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/869685/chrome-win.zip
    

    これで初期設定が完了です。~\AppData\Local\deno\deno_puppeteer以下に必要なものがインストールされます。
    余談ですがdeno runで直接http://~やdata://~のスクリプトが実行できるの便利ですよね…

これで、以下のようなコードが実行できるようになっているはずです。

import puppeteer from "https://deno.land/x/puppeteer@9.0.0/mod.ts";

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://www.yahoo.co.jp/");
await browser.close();

基本的なAPIはNode.js版と同じです。
top-level-awaitがデフォルトで使えるのでシンプルにかけていい感じです。

3
2
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
2