1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Python]Seleniumを用いたWebページスクリーンショット取得方法 メモ

Posted at
  • Seleniumを用いたWebページのスクリーンショット取得方法についてメモする。

プロジェクト構成

screenshot --- screenshot.py
			|_ chromedriver.exe
			|_ images

コード

  • screenshot.py
    • 実行時に指定したURLのWebページのスクリーンショットを取得する。
      * ページ内の特定画像を保存したい場合は、コメントアウト箇所を外し、対象画像のIDを指定する。
    • その他
      * コードと同一階層にchromedriverを配置する。chromedriverの取得方法はこちらを参照のこと。
      * imagesフォルダに取得結果を配置する。
import sys
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options

# 標準入力から対象ページのURLを取得
args = sys.argv
target_url = args[1]

options = Options()
options.add_argument('--headless')

with webdriver.Chrome("./chromedriver.exe", options=options) as driver:
    # ページ上のすべての要素が読み込まれるまで待機
    wait = WebDriverWait(driver, 15)
    driver.implicitly_wait(10)
    driver.get(target_url)
    wait.until(EC.presence_of_all_elements_located)

    # ウィンドウサイズ調整
    w = driver.execute_script("return document.body.scrollWidth;")
    h = driver.execute_script("return document.body.scrollHeight;")
    driver.set_window_size(w, h)

    # スクリーンショット取得
    # ページ全体を保存したい場合
    driver.save_screenshot("images/all_page_screenshot.png")

    # ページ内の特定画像を保存したい場合
    # png = driver.find_element_by_id('#対象画像のID').screenshot_as_png
    # with open('./images/target_image.png', 'wb') as f:
    #    f.write(png)
    # ブラウザクローズ
    driver.quit()

実行方法

python screenshot.py 取得対象ページURL

imagesフォルダにスクリーンショットが保存される。

参考情報

1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?