画像のダウンロードbySelenium

投稿者: | 2023-02-28
  • HPからアイテムのダウンロードリンクをJSONで取得する方法
  • Seleniumのimg.screenshot_as_pngは、指定した<img>要素のスクリーンショットをPNG形式で取得するメソッドです。
# P272

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
import time, os, json

# 画像の保存先を指定
SAVE_DIR = './s_images'
if not os.path.exists(SAVE_DIR):
    os.mkdir(SAVE_DIR)

result = []

# Chromeを起動
driver = webdriver.Chrome(
    service=ChromeService(ChromeDriverManager().install())
)

# 書道掲示板の一覧ページを開く
driver.get('https://uta.pw/shodou/index.php?master')
time.sleep(1)

# 画像一覧を得る
arts = driver.find_elements(By.CSS_SELECTOR,
                            '#recent_list > .article')
for art in arts:
    # imgを得る
    img = art.find_element(By.CSS_SELECTOR, 'img')
    src = img.get_attribute('src') # ソースURL
    alt = img.get_attribute('alt') # 代替テキスト
    print(alt, src)

    # 画像が切れるのを防ぐため少しずつスクロール
    driver.execute_script('window.scrollBy(0,100)')


    png_file = os.path.join(SAVE_DIR, os.path.basename(src)) # ソースURLのファイル名取得

    # 画像をバイナリ形式で保存する(ソースURLではなく、エレメントを書き込んでいる)
    with open(png_file, 'wb') as fp:
        fp.write(img.screenshot_as_png) # 実際に保存される

  # JSONに情報を保存
    result.append({
        'title': alt,
        'url': src,
        'file': png_file,
    })

# JSONを保存
with open('s_images.json', 'w', encoding='utf-8') as fp:
    json.dump(result, fp, indent=4, ensure_ascii=False)