google画像検索の結果から該当画像を取得、ローカル保存できるようにしたい(Python)

実現したいこと

google画像検索の結果から該当画像を取得、ローカル保存できるようにする

前提

Pythonでコードを作っています。
コードはChat-GPTとの対話で作りこんできました。
仕様としては、
・検索したい画像をテキスト入力する
・保存する画像数を入力する
以下の入力からgoogle画像検索に飛び、入力した画像数分だけローカル保存します。

発生している問題・エラーメッセージ

プログラムを実行すると特にエラーメッセージは発生せず終了しますが、所定のフォルダに画像が入りません。

該当のソースコード

Python

1from selenium.webdriver.common.by import By 2from selenium.webdriver.chrome.service import Service 3from selenium.webdriver.chrome.options import Options 4from selenium.webdriver.common.keys import Keys 5from selenium import webdriver 6import os 7import requests 8from bs4 import BeautifulSoup 9from selenium.webdriver.common.action_chains import ActionChains 10 11# プログラムの設定12search_text = input("検索したい画像のキーワードを入力してください: ")13num_images = int(input("保存する画像の数を入力してください: "))14output_directory = "images" # 保存先ディレクトリ15os.makedirs(output_directory, exist_ok=True)16 17# WebDriverの設定18webdriver_service = Service('C:/****セキュリティ上隠します****/driver/chromedriver_win32/chromedriver.exe') # ローカル環境にChromeDriverをインストールしてください19webdriver_options = Options()20#webdriver_options.add_argument('--headless') # ブラウザを表示せずに実行する場合はコメントアウト21webdriver = webdriver.Chrome(service=webdriver_service, options=webdriver_options)22 23# Google画像検索の実行24webdriver.get("https://www.google.com/imghp")25search_box = webdriver.find_element(By.NAME, "q")26search_box.send_keys(search_text)27search_box.send_keys(Keys.RETURN)28 29# 画像の収集と保存30image_count = 031while image_count < num_images:32 results = webdriver.find_elements(By.CSS_SELECTOR, "img.rg_i")33 34 for result in results:35 # サムネイルをクリックして拡大画像を表示36 webdriver.execute_script("arguments[0].click();", result)37 webdriver.implicitly_wait(2)38 39 # 拡大画像のURLを取得40 large_img = webdriver.find_element(By.CSS_SELECTOR, ".n3VNCb img")41 image_url = large_img.get_attribute("src")42 43 if image_url and image_url.startswith('http'):44 response = requests.get(image_url)45 image_count += 146 filename = f"{search_text}_{image_count}.jpg"47 filepath = os.path.join(output_directory, filename)48 with open(filepath, "wb") as f:49 f.write(response.content)50 print(f"保存: {filepath}")51 52 if image_count >= num_images:53 break54 55 # 次のページに移動56 try:57 next_button = webdriver.find_element(By.CSS_SELECTOR, "#smb")58 webdriver.execute_script("arguments[0].scrollIntoView(true);", next_button)59 webdriver.execute_script("window.scrollBy(0, -100);") # ボタンが隠れないように上にスクロール60 webdriver.execute_script("arguments[0].click();", next_button)61 webdriver.implicitly_wait(next_button = webdriver.find_element(By.CSS_SELECTOR, "#smb"))62 webdriver.execute_script("arguments[0].scrollIntoView(true);", next_button)63 webdriver.execute_script("window.scrollBy(0, -100);") # ボタンが隠れないように上にスクロール64 webdriver.execute_script("arguments[0].click();", next_button)65 webdriver.implicitly_wait(2)66 except:67 break68 69# WebDriverを閉じる70webdriver.quit()

試したこと

実行後、ブラウザが起動しgoogleの画像検索画面に飛んで、入力したテキストに関する画像が表示されるところまでは確認できています。

補足情報(FW/ツールのバージョンなど)

Python 3.11.3
Chrome バージョン: 114.0.5735.91
Chrome Driver: 114.0.5735.90
OS: Windows11 Pro

コメントを投稿

0 コメント