インストール
最初にHeadless Chromeに必要なパッケージを入れる。
参考:https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md
Ubuntuの場合
$ sudo apt install ca-certificates fonts-liberation gconf-service libappindicator1 libasound2 libatk-bridge2.0-0 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 lsb-release wget xdg-utils
プロジェクトにインストール
$ npm install --save puppeteer
使い方
初期化
const puppeteer = require('puppeteer');
async function init(){
const browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
const page = await browser.newPage();
}
終了
await browser.close();
ビューポートの設定
await page.setViewport({
width: 640,
height: 480,
deviceScaleFactor: 1,
});
スクリーンショット
// PNGとしてスクリーンショット
await page.screenshot({path: 'screenshot.png'});
// PDF出力
await page.pdf({path: 'page.pdf'});
ページ遷移
単純な遷移
await page.goto('http://example.com');
ネットワークの接続が終わるまでウエイト(ネットワークコネクションがなくなって500msのウエイト)
await page.goto('http://example.com',{waitUntil:networkidle0});
クリック
// clickの引数はcssのセレクタ
await page.click('tr:nth-child(5) input');
入力
// typeの第一引数はcssのセレクタ
// typeの第二引数は入力したい文字
await page.type('tr:nth-child(2) input', "test");
エレメントの存在確認
if (await page.$("#ID2")) {
// #ID2が存在する場合の処理
}
エレメントの属性取得
// ID4のテキスト取得
const text = await page.$eval('#ID4', (el) => el.innerText);
// ID5がdisabledかどうか
const disabled = await page.$eval('#ID5', (el) => el.disabled);
// .textのエレメントの文字列をすべて取得
const text_list = page.$$eval('.text', (elements) => {
return elements.map((ele) => ele.innerText);
});
いろんなウエイト
1000msのウエイト
await page.waitFor(1000);
ページ遷移時のウエイト
await page.waitForNavigation({
waitUntil: 'networkidle0',
});
通信されるまでウエイト(ページ遷移ではなくAjax等でウエイトしたいとき)
// matchを使っているのは、getクエリで後ろにパラメータがあってもマッチさせるため
await page.waitForResponse(response => response.url().match("http://example.com/api/get")),
任意のエレメントの状態が変わるまでウエイト
// #ID1のテキストが"Started"になるまで待つ。タイムアウト10000ms
await page.waitFor(() => document.querySelector('#ID1').innerText=="Started", { timeout: 10000 }),
コメント