Docker上で、Python + Selenium + Headless Chromeを使用してWEBスクレイピング

Docker上で、Python + Selenium + Headless Chromeを使用してWEBスクレイピングをしていきます。Dockerは、すでにインストール済みであるとします。

Dockerfile

  1. FROM python:3
  2.  
  3. RUN apt-get update && apt-get install -y unzip
  4.  
  5. #install google-chrome
  6. RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add && \
  7. echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | tee /etc/apt/sources.list.d/google-chrome.list && \
  8. apt-get update && \
  9. apt-get install -y google-chrome-stable
  10.  
  11. #install selenium
  12. RUN pip install selenium
  13.  
  14. #install ChromeDriver
  15. ADD https://chromedriver.storage.googleapis.com/2.45/chromedriver_linux64.zip /opt/chrome/
  16. RUN cd /opt/chrome/ && \
  17. unzip chromedriver_linux64.zip
  18.  
  19. ENV PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/chrome

新しいイメージを構築します。

  1. sudo docker build -t python-selenium-chrome .

WEBスクレイピング用のスクリプトを用意します。

test.py

  1. from selenium import webdriver
  2. from selenium.webdriver.common.keys import Keys
  3. import time
  4.  
  5. def _main():
  6. options = webdriver.ChromeOptions()
  7. options.add_argument('--headless')
  8. options.add_argument('--no-sandbox')
  9. driver = webdriver.Chrome(options=options)
  10.  
  11. driver.get('https://www.google.co.jp/')
  12. search = driver.find_element_by_name('q')
  13. search.send_keys('Python')
  14. search.send_keys(Keys.RETURN)
  15.  
  16. time.sleep(3)
  17. driver.save_screenshot('search_results.png')
  18.  
  19. driver.quit()
  20.  
  21. if __name__ == '__main__':
  22. _main()

コンテナを起動します。

  1. sudo docker run -it --rm -v $(pwd):/root python-selenium-chrome bash

スクリプトを実行します。

  1. cd /root
  2. python test.py

無事結果が得られました。

docker-seleniumを使っても良いかも…?

  1. docker run -d -p 4444:4444 -v /dev/shm:/dev/shm selenium/standalone-chrome:3.141.59-iron

test.py

  1. from selenium import webdriver
  2. from selenium.webdriver.common.keys import Keys
  3. from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
  4. import time
  5.  
  6.  
  7. def _main():
  8. driver = webdriver.Remote(
  9. command_executor='http:/0.0.0.0:4444/wd/hub',
  10. desired_capabilities=DesiredCapabilities.CHROME)
  11. driver.get('https://www.google.co.jp/')
  12. search = driver.find_element_by_name('q')
  13. search.send_keys('Python')
  14. search.send_keys(Keys.RETURN)
  15. time.sleep(3)
  16. driver.save_screenshot('search_results.png')
  17. driver.quit()
  18. if __name__ == '__main__':
  19. _main()

コメントする

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です