LoginSignup
2
4

More than 3 years have passed since last update.

CloudRun で Firefox ヘッドレスブラウザを動かしてスクリーンショットを撮る

Posted at

最近話題の CloudRun で Firefox ヘッドレスブラウザを実行して、スクリーンショットを返すサーバレスを試してみます。なぜ Chrome ではなく Firefox かというと、Web フォント(日本語)の unicode-range がうまく動かないので仕方なく Firefox にしています。Firefox はちゃんと動く。最高。

Docker

FROM selenium/standalone-firefox

WORKDIR /app
ADD /app .

EXPOSE 8000

CMD ["python", "server.py"]

selenium/standalone-firefox という Firefox が入っている良い感じのコンテナがあるので、これを使います。このコンテナには Python2.7 が入っているので、Python で Web サーバを構築します。僕は Python は初心者です。

Web サーバ

server.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import SimpleHTTPServer as s
import BaseHTTPServer as b
import subprocess
class MyHandler(s.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.make_screenshot()
    def make_screenshot(self):
        subprocess.call(['firefox', '-screenshot', '/tmp/screenshot.png', 'http://example.com/'])
        self.send_response(200)
        self.send_header('Content-type', 'image/png')
        self.end_headers()
        self.wfile.write(open('/tmp/screenshot.png', 'rb').read())
host = '0.0.0.0'
port = int(os.environ.get('PORT', 8000))
httpd = b.HTTPServer((host, port), MyHandler)
print('ポート:%s' % port)
httpd.serve_forever()

firefoxscreenshot オプションを渡すとスクリーンショットを保存してくれます。便利。あとは CloudRun 実行時に環境変数で提供されるポート番号を利用して Web サーバを起動するだけ。

CloudRun へデプロイ

gcloud components install beta
gcloud components update
gcloud auth login
gcloud config set project [PROJECT_NAME]
gcloud builds submit --tag gcr.io/[PROJECT_NAME]/firefox-headless-container
gcloud beta run deploy --image gcr.io/[PROJECT_NAME]/firefox-headless-container

これだけで OK 。非常に簡単。正常にデプロイできれば URL が発行されるので、そこにアクセスするとスクリーンショットの画像が返ってきます。

2
4
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
2
4