スクレイピング環境構築と実践

1. WSLインストール後の初期設定

WSLをインストールしたら、まずはパッケージのアップデートを行います。

sudo apt update
sudo apt upgrade -y

2. Pythonのインストール

Pythonがインストールされているか確認します。

python3 --version

もしインストールされていない場合は、以下のコマンドでインストールできます。

sudo apt install python3 python3-pip python3-venv -y

3. 仮想環境の作成

仮想環境を作成してPythonパッケージの管理を行います。

python3 -m venv venv

仮想環境のアクティベート:

source venv/bin/activate

仮想環境を終了する場合:

deactivate

4. BeautifulSoupとRequestsのインストール

基本的なスクレイピングにはBeautifulSouprequestsを使用します。

pip install beautifulsoup4
pip install requests

5. BeautifulSoupの使い方

以下のようにインポートし、WebページのHTMLを取得してパースします。

import requests
from bs4 import BeautifulSoup

url = 'https://www.example.com'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')

主要なパーサー

  • html.parser: 標準ライブラリ。追加インストール不要
  • lxml: 高速に処理可能
  • html5lib: HTML5の厳密なパースが可能

6. 情報の抽出方法

1. CSSセレクタの利用

elems = soup.select('div.article > h2.title > a')
for elem in elems:
    print(elem.text)
    print(elem['href'])

2. findfind_allの利用

# 最初の一致要素のみ取得
elem = soup.find('h2', class_='title')
print(elem.text)

# すべての一致要素を取得
elems = soup.find_all('h2', class_='title')
for elem in elems:
    print(elem.text)

7. Seleniumの導入と使い方

動的に生成されるページの情報を取得したい場合、Seleniumが必要です。

ChromeとChromeDriverのインストール

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo apt install ./google-chrome-stable_current_amd64.deb -y

wget https://storage.googleapis.com/chrome-for-testing-public/135.0.7049.95/linux64/chromedriver-linux64.zip
sudo apt install unzip -y
unzip chromedriver-linux64.zip
chmod +x chromedriver-linux64/chromedriver
sudo mv chromedriver-linux64/chromedriver /usr/local/bin/chromedriver

ChromeとDriverのバージョン確認:

google-chrome --version
chromedriver --version

8. Seleniumでの基本操作

以下はSeleniumを使った基本的な操作の例です。

from selenium import webdriver
from selenium.webdriver.common.by import By

# ブラウザの起動
driver = webdriver.Chrome()
driver.get('https://www.example.com')

# 要素の取得
title = driver.find_element(By.TAG_NAME, 'h1')
print(title.text)

# ブラウザの終了
driver.quit()

主な操作:

  • find_element: 最初に一致する要素を取得
  • find_elements: すべての一致する要素をリストで取得
  • click(): クリック操作
  • send_keys(): テキストの入力

9. プロジェクト例:Kikkomanレシピのスクレイピング

import requests
from bs4 import BeautifulSoup
import csv

url = 'https://www.kikkoman.co.jp/homecook/search/recipe'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')

recipes = []
for card in soup.select('.recipe-card'):
    title = card.select_one('.title').text
    link = card.select_one('a')['href']
    recipes.append([title, link])

with open('kikkoman_recipes.csv', mode='w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(['Title', 'Link'])
    writer.writerows(recipes)

print('スクレイピング完了: kikkoman_recipes.csvに保存されました')