LoginSignup
2

More than 3 years have passed since last update.

headless-chrome を Debian ベースのイメージ上で動かす

Posted at

スクレイピングで js を読み込みたい

Mac os でローカルの中だけでやる分には、いまだに phantom.js が快適に動いてくれるので、ヘッドレスブラウザの利用が簡単なんだけれども
Cloud Run で使用したかったので、公式のpythonイメージで動作確認しようと思ったら、意外とややこしかったのでメモしておく

訳わからん情報が溢れてる

どうやら phantom.js は更新をやめてしまうということだったので、大人しく headless-chrome を使用することにしたけど
工数を使用したくなかったので、他の人達の記事を漁った
でも僕はアホなので、記事を見てもとにかくわからんかった、もう自分でなんとかすることにした

結論

特に難しいことはなく、以下の条件を満たせば簡単に動く

chrome 本体をダウンロード
chrome 本体に合ったバージョンのドライバをダウンロード
起動時のオプションを適切に設定

Dockerfile

使用したベースイメージ

# Use the official Python image.
# https://hub.docker.com/_/python
FROM python:3.7

Chrome 本体のダウンロードをする、インストール時のバージョンは必ず見ておくこと

RUN sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list'
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN apt update
RUN apt install google-chrome-stable -y

Driver のダウンロードする、先にChromeのバージョンに一番近いやつを探す
https://chromedriver.storage.googleapis.com/
そんで、本体のバージョンに一番近い最新版を探す、今回は80台だったからこう
https://chromedriver.storage.googleapis.com/LATEST_RELEASE_80

見つけた番号でダウンロード&解凍するよ

RUN wget https://chromedriver.storage.googleapis.com/80.0.3987.106/chromedriver_linux64.zip
RUN unzip chromedriver_linux64.zip -d /usr/bin/

もちろんだけど、この段階で両方ともPATHが見える様にしておくこと

which chromedriver
witch google-chrome

こんだけでOK
あとは使用するだけ、一応使用例も書いとく

app.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup


URL = "https://example.jp"


def get_trends():
    try:
        options = Options()
        options.add_argument('--headless')
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')

        driver = webdriver.Chrome(options=options)
        driver.get(URL)
        html = driver.page_source.encode('utf-8')  # more sophisticated methods may be available
        soup = BeautifulSoup(html, "lxml")

終わり

ぶっちゃけメモ

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