LoginSignup
4
2

WSL(Windows Subsystem for Linux)上のUbuntuでSeleniumとChromeDriverを使用してWebスクレイピング

Last updated at Posted at 2023-07-09

WSL(Windows Subsystem for Linux)上のUbuntuでSeleniumとChromeDriverをセットアップして、PythonからWebスクレイピングする方法を解説します。

環境

  • OS: Ubuntu 20.04.6 LTS (WSL上)
  • Python: 3.8.10
  • Selenium: 4.10.0
  • Architecture: x86_64
  • CPU: AMD Ryzen 5 1600X Six-Core Processor

1. 必要なパッケージのインストール

まず、Ubuntuに必要なパッケージをインストールします。以下のコマンドを実行します。

sudo apt-get update
sudo apt-get install -y libatk1.0-0 fonts-ipafont
sudo fc-cache -fv

2. Seleniumとwebdriver_managerのインストール

PythonでSeleniumを使用するために、Seleniumとwebdriver_managerをインストールします。

pip install -U selenium webdriver_manager

3. Google ChromeとChromeDriverのインストール

Google ChromeとChromeDriverをインストールします。

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb

wget https://chromedriver.storage.googleapis.com/2.41/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
sudo mv chromedriver /usr/bin/chromedriver
sudo chown root:root /usr/bin/chromedriver
sudo chmod +x /usr/bin/chromedriver

4. Pythonコードの作成

最後に、以下のPythonコードを作成します。

# coding: UTF-8
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options

# Setup Chrome options
options = Options()
options.add_argument("--headless") # Ensure GUI is off. Remove this line if you want to see the browser navigating.

# Set path to chromedriver as a service
webdriver_service = Service(ChromeDriverManager().install())

# Set the driver
driver = webdriver.Chrome(service=webdriver_service, options=options)

# Get website data
driver.get("https://www.google.com")

# Take a screenshot
driver.save_screenshot("screenshot.png")

# Quit the driver
driver.quit()

screenshot.png

以上の手順により、WSL上のUbuntuでSeleniumとChromeDriverを使用して、PythonからWebスクレイピングが可能になります。特に、文字化け問題やドライバのセットアップ問題を解決したため、日本語のWebページも問題なく取得できます。

この記事が、PythonとSeleniumを使用してWSL上のUbuntuでWebスクレイピングを行う方々の参考になれば幸いです。

上記の記事はあくまで一例であり、実際の環境や要件によって変更が必要かもしれません。適宜、自身の状況に合わせて内容を調整してください。

4
2
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
4
2