LoginSignup
0
0

More than 1 year has passed since last update.

ChatGPT-4にSeleniumで画像キャプチャするソースコードを生成してもらってみた

Last updated at Posted at 2023-03-15

条件
seleniumを使って、引数として入力したurlの画面をキャプチャするプログラムを書いてください。ただし、条件は以下に従って下さい。
・言語はPython3を使用
・開発はMac
・複数のURLに対応
・実行する際の引数はターミナルで指定
・スクロールした時の画面をキャプチャする
・キャプチャした画面を、10MB未満で保存する

capture_screenshot.py
import sys
import os
from io import BytesIO
from PIL import Image
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def capture_website(url, output_path):
    # Chrome WebDriverをヘッドレスモードで設定
    options = Options()
    options.headless = True
    driver = webdriver.Chrome(options=options)

    # 指定されたURLを読み込み、ページの一番下までスクロール
    driver.get(url)
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    driver.implicitly_wait(3)

    # スクリーンショットをキャプチャし、WebDriverを閉じる
    image_data = BytesIO(driver.get_screenshot_as_png())
    driver.quit()

    # キャプチャした画像をPIL Imageオブジェクトに変換
    img = Image.open(image_data)
    img_quality = 90
    img_size = img.size

    # 画像サイズが10MB未満になるまで、画像品質を下げる
    while img_size > 10 * 1024 * 1024:
        img.save(output_path, "JPEG", quality=img_quality)
        img_size = os.path.getsize(output_path)
        img_quality -= 5

    # 調整された品質で画像を保存
    img.save(output_path, "JPEG", quality=img_quality)
    print(f"Screenshot saved at {output_path}")

if __name__ == "__main__":
    # コマンドライン引数に最低1つのURLが指定されているかチェック
    if len(sys.argv) < 2:
        print("Usage: python capture_website_chrome.py <url1> [<url2> <url3> ...]")
        sys.exit(1)

    # コマンドライン引数からURLのリストを取得
    urls = sys.argv[1:]

    # 各URLのスクリーンショットをキャプチャし、保存
    for i, url in enumerate(urls, 1):
        output_path = f"screenshot_{i}.jpeg"
        capture_website(url, output_path)


0
0
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
0
0