LoginSignup
12
14

More than 5 years have passed since last update.

xvfbwrapper + selenium でpythonからweb画面キャプチャ

Last updated at Posted at 2015-06-17

xvfbwrapper + selenium を使ってpythonから仮想ディスプレイのweb画面をキャプチャする方法を紹介します.

環境

  • Ubuntu14.04
  • python 2.7.10
  • 2015/06/18時点で最新版のFirefox

下準備

まず必要ライブラリ等をインストールします

apt-get install xvfb
pip install xvfbwrapper
pip install selenium

Xvfbは,仮想的なフレームバッファを実現するソフトウェアです.
今回はこれを使って仮想的なディスプレイを作り,firefoxでWebブラウザを立ち上げ,ページのスクリーンショットを撮ります.
xvfbwrapperはその名の通り,XvfbのpythonWrapper, seleniumは自動テストを行ったり,Webサイトを操作して何かを取得したりしたい時に便利です.
詳しくはこちら

日本語フォントのインストール

入れないとスクリーンショットが文字化けします.

$ wget -q https://www.ubuntulinux.jp/ubuntu-ja-archive-keyring.gpg -O- | sudo apt-key add -
$ wget -q https://www.ubuntulinux.jp/ubuntu-jp-ppa-keyring.gpg -O- | $ sudo apt-key add -
$ sudo wget https://www.ubuntulinux.jp/sources.list.d/quantal.list -O /etc/apt/sources.list.d/ubuntu-ja.list
$ sudo apt-get update
$ sudo apt-get install ubuntu-defaults-ja

キャプチャ

下準備が済んだので実際にキャプチャしてみましょう.

from selenium import webdriver
from xvfbwrapper import Xvfb


class CapturePages(object):

    def __init__(self, _width, _height):

        # adapting to japanease 
        fp = webdriver.FirefoxProfile()
        fp.set_preference('intl.accept_languages', 'ja-JP, ja')
        self.xvfb = Xvfb(width=_width, height=_height)
        self.xvfb.start()
        # getting webdriver
        self.browser = webdriver.Firefox(firefox_profile=fp)


    def capPage(self, page, file_name):
        # waiting 2 sec
        self.browser.implicitly_wait(2)
        # going to webpage
        self.browser.get(page)
        # screen capture
        self.browser.save_screenshot(file_name)
        # closing web browser
        self.browser.close()

    def endCapture(self):
        self.xvfb.stop()
        self.browser.quit()

if __name__ == '__main__':
    capture = CapturePages(1280, 720)
    capture.capPage("https://www.google.co.jp", "sample.png")
    capture.endCapture()

sample.pngにgoogleのトップページが保存されているはずです.

参考サイト

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