Docker上で、Python + Selenium + Headless Chromeを使用してWEBスクレイピングをしていきます。Dockerは、すでにインストール済みであるとします。
Dockerfile
FROM python:3
RUN apt-get update && apt-get install -y unzip
#install google-chrome
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add && \
echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | tee /etc/apt/sources.list.d/google-chrome.list && \
apt-get update && \
apt-get install -y google-chrome-stable
#install selenium
RUN pip install selenium
#install ChromeDriver
ADD https://chromedriver.storage.googleapis.com/2.45/chromedriver_linux64.zip /opt/chrome/
RUN cd /opt/chrome/ && \
unzip chromedriver_linux64.zip
ENV PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/chrome
新しいイメージを構築します。
sudo docker build -t python-selenium-chrome .
WEBスクレイピング用のスクリプトを用意します。
test.py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
def _main():
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
driver = webdriver.Chrome(options=options)
driver.get('https://www.google.co.jp/')
search = driver.find_element_by_name('q')
search.send_keys('Python')
search.send_keys(Keys.RETURN)
time.sleep(3)
driver.save_screenshot('search_results.png')
driver.quit()
if __name__ == '__main__':
_main()
コンテナを起動します。
sudo docker run -it --rm -v $(pwd):/root python-selenium-chrome bash
スクリプトを実行します。
cd /root python test.py
無事結果が得られました。

docker-seleniumを使っても良いかも…?
docker run -d -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-chrome:3.141.59-iron
test.py
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
def _main():
driver = webdriver.Remote(
command_executor='http:/0.0.0.0:4444/wd/hub',
desired_capabilities=DesiredCapabilities.CHROME)
driver.get('https://www.google.co.jp/')
search = driver.find_element_by_name('q')
search.send_keys('Python')
search.send_keys(Keys.RETURN)
time.sleep(3)
driver.save_screenshot('search_results.png')
driver.quit()
if __name__ == '__main__':
_main()