それマグで!

知識はカップより、マグでゆっくり頂きます。 takuya_1stのブログ

習慣に早くから配慮した者は、 おそらく人生の実りも大きい。

Chromeのヘッドレスモードで快適生活

chrome のヘッドレスモードで起動して遊ぶ

Chromeのヘッドレスモードは便利ですよね。

macOS にも Chrome のヘッドレスモードがやってきます。

MacOSだと長らく動かなかったので、あれこれトリックを使っててめんどくさかったんです。ようやく陽の光が!

準備したもの

Chrome >=59 であればいいので、Dev チャンネルから持ってきた。そのうち通常リリースに含まれると思う。

f:id:takuya_1st:20170418185344p:plain

インストール

/Applications/Chrome-dev-59.app

という名前で保存した。この名前はあとで open -a するのに必要

起動

とりあえず。ヘッドレスモードで起動する

open -a  Chrome-dev-59.app --args  --headless chrome://help/

起動した!

CMD-Q で終了すら出来ない、単純なAppが起動する。

f:id:takuya_1st:20170418185733p:plain f:id:takuya_1st:20170418185749p:plain

remote-debugging-port を使って遊ぶ

open -a  Chrome-dev-59.app --args  --headless --remote-debugging-port=9222 chrome://help/

node で遊ぶ

npm install chrome-remote-interface

コードを書く

const CDP = require('chrome-remote-interface')

CDP( ( client ) => {
    //Extract used Devetools domains.
    const { Page, Runtime } = client;
    // Enable events on domains we are intersted in.
    Promise.all( [
      Page.enable()
    ]).then(  () => {
      return Page.navigate( { url: "http://t.co"});
    })

    // Evaluate outerHTML after page has loaded.
    Page.loadEventFired( () => {
      Runtime.evaluate( {expression: 'document.body.outerHTML'} ).then( (result) =>{
          console.log( result.result.value );
          client.close();
        })
    })

}).on('error', (err) => {
  console.error('Cannot connect to Browser:', err);
})

サンプルコードはここから → https://github.com/cyrus-and/chrome-remote-interface

実行結果

takuya@headless-test$ node  sample.js
<body>

    <div id="main">
      <a href="http://twitter.com" class="bird"><img src="/static/images/bird.png" alt="Twitter"></a>
      <p><a href="http://twitter.com">Twitter</a> uses the <strong>t.co</strong> domain as part of a service to protect users from harmful activity, to provide value for the developer ecosystem, and as a quality signal for surfacing relevant, interesting Tweets.</p>
      <a class="back" href="http://twitter.com">Back to Twitter</a>
      <a class="more" href="http://help.twitter.com/entries/109623">Learn more</a>
    </div>

    <div class="footer">
      <span>© <script type="text/javascript">document.write(new Date().getFullYear());</script>2017 Twitter</span>
      <a href="http://twitter.com/about">About Us</a>
      <a href="http://twitter.com/about/contact">Contact</a>
      <a href="http://blog.twitter.com/">Blog</a>
      <a href="http://status.twitter.com/">Status</a>
      <a href="http://dev.twitter.com">API</a>
      <a href="http://help.twitter.com/">Help</a>
      <a href="http://twitter.com/jobs">Jobs</a>
      <a href="http://twitter.com/tos">TOS</a>
      <a href="http://twitter.com/privacy">Privacy</a>
    </div>


</body>

あとは、普通に遊べる。

ああ、これでずっと楽にCookie必須なWEBサイトの中で遊べるわ。WEBブラウザを操縦するのは遅いからスクレイピングには向かいないけど。。。自動実行とかだとうまくいく。