okpy

Pythonエンジニア兼テックリーダーが、多くのプロジェクトとチーム運営から得た実践的な知識を共有するブログです。

PythonとSeleniumでの画像収集

🐍 Python + SeleniumGoogle画像を自動収集するスクリプト【完全解説付き】

機械学習用のデータセットを作成したいときや、素材画像を効率的に集めたいとき、毎回手作業で画像を保存するのは非常に手間がかかります。そこで今回は、Python + Selenium を使って、Google画像検索から自動で画像を取得して保存するスクリプトを紹介します。


✅ このスクリプトでできること

  • 指定した検索キーワードでGoogle画像検索を実行
  • 上位の画像URLを取得し、ローカルにJPEG形式で保存
  • キーワードごとにフォルダ分けして保存

🧰 使用するライブラリ

  • selenium:ブラウザ操作の自動化
  • requests:画像データの取得
  • Pillow (PIL):画像処理と保存
  • hashlib:画像ファイル名をユニークにするためのハッシュ化
  • io, time, os:基本的なPython標準ライブラリ

📂 ファイル構成と入力例

  • search_list.txt:検索ワードを1行ごとに記載(例:cat, dog, car

🧠 ソースコード全体(コメント付き)

以下が、あなたが提供してくれたソースコードです。

import os
import time
from selenium import webdriver
import chromedriver_binary
from PIL import Image
import io
import requests
import hashlib
import os.path

filename = 'search_list.txt'

# テキストファイルの内容を読み込む関数
def load_doc(filename):
    file = open(filename, 'r')
    text = file.read()
    file.close()
    return text

# 各行のキーワードをセットとして取得
def load_set(filename):
    doc = load_doc(filename)
    dataset = list()
    for line in doc.split('\n'):
        if len(line) < 1:
            continue
        identifier = line.split('.')[0]
        dataset.append(identifier)
    return set(dataset)

# メイン処理(1キーワードごとの画像検索と保存)
def run(search_keyword):
    sleep_between_interactions = 2  # クリック後の待機時間
    download_num = 3  # ダウンロードする画像数
    query = search_keyword

    search_url = "https://www.google.com/search?safe=off&site=&tbm=isch&source=hp&q={q}&oq={q}&gs_l=img"

    options = webdriver.ChromeOptions()
    wd = webdriver.Chrome(chrome_options=options)
    wd.get(search_url.format(q=query))

    # サムネイル画像を取得(ここでエラーが出る場合はセレクタを確認)
    thumbnail_results = wd.find_elements_by_css_selector("img.rg_i")

    # 各画像のURLを取得
    image_urls = set()
    for img in thumbnail_results[:download_num]:
        try:
            img.click()
            time.sleep(sleep_between_interactions)
        except Exception:
            continue
        # 表示された画像のURLを取得
        url_candidates = wd.find_elements_by_class_name('n3VNCb')
        for candidate in url_candidates:
            url = candidate.get_attribute('src')
            if url and 'https' in url:
                image_urls.add(url)

    time.sleep(sleep_between_interactions + 3)
    wd.quit()

    # 保存用フォルダ作成
    image_save_folder_path = query
    if not os.path.isdir(image_save_folder_path):
        os.makedirs(image_save_folder_path)

    # 画像をダウンロードして保存
    for url in image_urls:
        try:
            image_content = requests.get(url).content
        except Exception as e:
            print(f"ERROR - Could not download {url} - {e}")
            continue

        try:
            image_file = io.BytesIO(image_content)
            image = Image.open(image_file).convert('RGB')
            file_path = os.path.join(image_save_folder_path, hashlib.sha1(image_content).hexdigest()[:10] + '.jpg')
            with open(file_path, 'wb') as f:
                image.save(f, "JPEG", quality=90)
            print(f"SUCCESS - saved {url} - as {file_path}")
        except Exception as e:
            print(f"ERROR - Could not save {url} - {e}")

# キーワードごとに実行
search_keywords = load_set(filename)
for search_keyword in search_keywords:
    run(search_keyword)

📝 注意点と改善ポイント

  • find_elements_by_css_selectorfind_elements_by_class_nameSelenium 4以降で非推奨 です。以下のように変更することが推奨されます:
  from selenium.webdriver.common.by import By
  wd.find_elements(By.CSS_SELECTOR, "img.rg_i")
  • GoogleのHTML構造は変更されることがあるため、画像クラス名 n3VNCb が使えなくなる場合があります。その場合は、開発者ツールで確認しましょう。

  • スクレイピングの仕様上、Google利用規約に反しない範囲で適切に使いましょう。


📦 実行後の構成例

project/
├── search_list.txt
├── cat/
│   ├── a1b2c3d4e5.jpg
│   └── ...
├── dog/
│   ├── f6g7h8i9j0.jpg
│   └── ...

🎉 まとめ

このスクリプトを使えば、検索ワードを与えるだけでGoogle画像を自動で収集して整理されたフォルダに保存することができます。今後、以下のような拡張も可能です:

  • 画像サイズのフィルターを追加
  • 収集枚数を動的に変更
  • ファイル名にキーワードや連番を追加

SeleniumPythonの組み合わせで、ブラウザを自在に操作する力を身につけましょう!