Python, Selenium, Dockerを組み合わせてスクレイピング環境を構築する方法について説明します。

DockerとSeleniumの組み合わせ

Python実行環境とSelenium実行環境を別のコンテナとして準備します。Selenium実行環境はdocker-seleniumのChromeがインストールされたstandaloneイメージを使用します。

version: "3"
services:
  selenium:
    image: selenium/standalone-chrome:4.1.4-20220427
    ports:
      - 4444:4444
      - 7900:7900
    volumes:
      - /dev/shm:/dev/shm
  app:
    build: .
    ports:
      - 8888:8888
    volumes:
      - .:/app
    environment:
      SELENIUM_URL: http://selenium:4444/wd/hub
    command: jupyter-notebook --port=8888 --ip=0.0.0.0 --allow-root --NotebookApp.token=''
    tty: true

Pythonスクリプト

Pythonスクリプトでは、環境変数SELENIUM_URLを使用してSeleniumコンテナに接続します。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import os
import time

url = "https://www.google.com"
keyword = "スクレイピング"

driver = webdriver.Remote(
    command_executor=os.environ["SELENIUM_URL"],
    options=webdriver.ChromeOptions()
)

driver.implicitly_wait(10)
driver.get(url)
driver.find_element(By.NAME, "q").send_keys(keyword + Keys.RETURN)
time.sleep(5)
driver.quit()

このように、Python, Selenium, Dockerを組み合わせることで、効率的なスクレイピング環境を構築することができます。.

投稿者 admin

コメントを残す

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