12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Google謹製Chrome操作ライブラリPuppeteerを使ってみた

Last updated at Posted at 2018-10-04

Puppeteerとは

GoogleChromeが提供しているChrome操作できるNode.jsライブラリ。

GoogleChrome/puppeteer: Headless Chrome Node API

デフォルトはヘッドレスブラウザだが、設定で解除できる。

puppet(操り人形)のように、Chromeを操作。

install

$ node -v
v10.11.0

$ npm i puppeteer

$ npm ls puppeteer
...
└── puppeteer@1.8.0

screenshotを取得

// screen_shot.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 screen_shot.js

結果

screenshot_example.png

ウェブ画面のPDFを生成

// create_pdf.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: 'create_pdf_sample.pdf', format: 'A4'});

  await browser.close();
})();
node create_pdf.js

結果

Screen Shot 2018-10-04 at 23.13.07.png

GitHubログイン

// ログイン情報を書いたファイルを準備
// $ cat creds.js
module.exports = {
    username: 'USERNAME',
    password: 'PASSWORD'
}
// ログイン処理本体
// $ cat github_login.js
const puppeteer = require('puppeteer');

(async () => {

  const browser = await puppeteer.launch({
    headless: false // 今回はあえてヘッドレスを解除して起動
  });
  const page = await browser.newPage();
  await page.goto('https://github.com/login');

  // github.com DOM要素セレクタ
  const USERNAME_SELECTOR = '#login_field';
  const PASSWORD_SELECTOR = '#password';
  const BUTTON_SELECTOR = '#login > form > div.auth-form-body.mt-3 > input.btn.btn-primary.btn-block';

  // ログイン情報の読み込み
  const CREDS = require('./creds');

  // セレクタをクリックして、ログイン情報をタイプ入力
  await page.click(USERNAME_SELECTOR);
  await page.keyboard.type(CREDS.username);

  await page.click(PASSWORD_SELECTOR);
  await page.keyboard.type(CREDS.password);

  // ログインボタンをクリック
  await page.click(BUTTON_SELECTOR);

  await page.waitForNavigation();

})();
// ファイルを実行するとChromeが起動して処理を実行。
node github_login.js

コマンド実行後の画面動作

Kapture 2018-10-04 at 23.04.24.gif

参照

その他サンプルが多数以下に掲載されているので参考になる。
checkly/puppeteer-examples: Puppeteer example scripts for running Headless Chrome from Node. Run them at https://puppeteersandbox.com

12
11
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
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?