環境
- Mac
- Node.js v15.3.0
- Npm 7.0.14
- puppeteer 5.5.0
■ Puppeteer導入
1. Puppeteerインストール
npm install puppeteer
2. 動作確認
- スクリーンショット取得
example.js
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({path: 'example.png'});
await browser.close();
})();
node example.js
- PDF取得
hn.js
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle2'});
await page.pdf({path: 'hn.pdf', format: 'A4'});
await browser.close();
})();
node hn.js
- viewport取得
get-dimensions.js
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// Get the "viewport" of the page, as reported by the page.
const dimensions = await page.evaluate(() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio
};
});
console.log('Dimensions:', dimensions);
await browser.close();
})();
node get-dimensions.js
■ 実行オプション
- ブラウザ表示
const browser = await puppeteer.launch({headless: false}); // default is true
- Chromiumのバージョン指定
const browser = await puppeteer.launch({executablePath: '/path/to/Chrome'});