LoginSignup
1
3

More than 3 years have passed since last update.

Docker で ヘッドレス Chrome を動かしてスクレイピングする

Last updated at Posted at 2019-07-07

ヘッドレス Chrome を動かしてウェブサイトをスクレイピングするための Docker イメージを作成しました。

この Docker イメージは指定された URL をヘッドレス Chrome で取得して HTML を標準出力にダンプします。
手軽に Vue.js や React で実装されたページの HTML を取得するときに便利です。

$ docker pull grohiro/headless-chrome
$ docker run --rm -t grohiro/headless-chrome http://www.google.com/ | head -5 | cut -b -100
<!DOCTYPE html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="ja"><head><meta charset="UTF-8"><meta
"clickmod";else{var f=b.which||b.keyCode||b.key;D&&3==f&&(f=13);if(13!=f&&32!=f)f=!1;else{var m=B(b)
b;e.event=A;a.i.push(e)}if("touchend"==e.event.type&&e.event._mouseEventsPrevented){b=e.event;for(va
c&&(c="focusout"),e=w(b,e),b.attachEvent("on"+c,e));return{m:c,l:e,capture:f}}},O=function(a,d){if(!

単一のページを取得したいだけならプログラムの中から Docker を直接起動して HTML を取得できます。

<?php
// PHPの例
$cmd = "docker run --rm -t grohiro/headless-chrome http://www.google.com";
exec($cmd, $output, $status);
if ($status !== 0) {
  throw new \Exception("コマンドの実行がエラーになりました");
}
$html = implode("\n", $output);
$dom = @DOMDocument::loadHTML($html);
$xpath = new DOMXPath($dom);
echo $xpath->query('//title')[0]->nodeValue;
// => Google

Docker イメージの作成は https://qiita.com/rotelstift/items/7dafcdcae3ca18b65b26 こちらの記事を参考にしました。

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