0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[macOS] 次々にWebサイトを表示して スクリーンショットを取得するスクリプト [Python][Selenium]

Posted at

✅技術要素

  • 表示するサイトのURLは、あらかじめテキストファイルに記述しておきます
  • Seleniumを使用して、Safariにサイトを表示します
  • SafariのウインドウIDを、AppleScriptを使用して取得します
  • screencaptureコマンドを使用して、Safariのスクリーンショットを取得します
  • 全体をPythonスクリプトで実装します

macOS 26.1 (25B78)
Safari 26.1 (21622.2.11.11.9)
Python 3.13.9
Selenium 4.38.0


✅URLリスト(テキストファイル)

  • 単純に、1行:1URLで記述します

    URL_list.txt
    https://qiita.com/nak435/items/800dbda782f4fe9c7df1
    https://qiita.com/nak435/items/67aca33ca49b6f328faa
    https://qiita.com/nak435/items/d6d9782d43c5e948447b
    https://qiita.com/nak435/items/02fb97a666f0596c0316
    

✅AppleScriptを使用してSafariのウインドウIDを取得する

osascript -e 'tell app "Safari" to id of window 1'
  • Safariのウインドウを複数開いている場合に、どのウインドウかを番号で指定します

    実行例
    % osascript -e 'tell app "Safari" to id of window 1'
    6784
    
    % osascript -e 'tell app "Safari" to id of window 2'
    109
    

開いた順に、1, 2, 3, ...とは、ならないようです!
(後から開いたウインドウのウインドウIDの数値は大きい)
複数のSafariウインドウが開いている場合は 要注意。


ここで取得したウインドウIDを指定して、次のscreencaptureコマンドを使用して、Safariウインドウのスクリーンショットを取得します。

✅screencaptureコマンドでスクリーンショットを取得する

  • screencaptureコマンドはmacOS標準。特別なインストール不要で使用できます

    screencapture -x -o -l<WindowID> filename.png
    

     -x シャッター音を鳴らさない
     -o 影を付けない

    実行例
    screencapture -x -o -l6784 scr_001.png
    

  • スクリーンショットの保存先ディレクトリは、次のコマンドで設定/参照できます

    保存先を設定する
    defaults write com.apple.screencapture location 保存先パス
    
    保存先を確認する
    defaults read com.apple.screencapture location
    
    実行例
    % defaults read com.apple.screencapture location
    ~/Pictures/Screenshots
    

✅SeleniumでSafariを制御するために

  • あらかじめ、Safari「設定」→「デベロッパ」タブ →「リモートオートメーションを許可」にチェックを付ける必要があります

    safari-developer.png

  • Seleniumは事前にインストールしてください

    pip install -U selenium
    




必要な要素が揃ったので、それをPythonスクリプトに組み立てます。


✅Pythonスクリプト

url_scr.py
import time
import subprocess
from selenium import webdriver

# Open Safari
driver = webdriver.Safari()
driver.get("https://qiita.com/") #dummy
driver.implicitly_wait(2)

# window resize
driver.set_window_position(0, 0)
driver.set_window_size(1280, 1440)

# get WindowID of 1st window of safari
data = subprocess.run("osascript -e 'tell app \"Safari\" to id of window 1'", capture_output=True, shell=True, text=True)
windowID = data.stdout[0:-1]
print(f"Safari windowID: {windowID}")

url_count=0

# open url list
path = r"./URL_list.txt"
with open(path, "r", encoding='utf-8') as f:
    for line in f:
        url = line[0:-1]
        url_count += 1
        print(f'URL[{url_count}] {url}')

        # get url
        driver.get(url)
        driver.implicitly_wait(2)
        time.sleep(1)

        outputfile = f'scr-{url_count:03d}.png'
        try:
            subprocess.check_output(['screencapture', '-x', '-o', f'-l{windowID}', outputfile], shell=False)
            print(f'URL[{url_count}] screenshot save to {outputfile}')
        except subprocess.CalledProcessError as e:
            print('Python error: [%d]\n{}\n'.format(e.returncode, e.output))

driver.quit()
実行結果
% python url_scr.py
Safari windowID: 7193
URL[1] https://qiita.com/nak435/items/800dbda782f4fe9c7df1
URL[1] screenshot save to scr-001.png
URL[2] https://qiita.com/nak435/items/67aca33ca49b6f328faa
URL[2] screenshot save to scr-002.png
URL[3] https://qiita.com/nak435/items/d6d9782d43c5e948447b
URL[3] screenshot save to scr-003.png
URL[4] https://qiita.com/nak435/items/02fb97a666f0596c0316
URL[4] screenshot save to scr-004.png

% ls scr*.png
scr-001.png
scr-002.png
scr-003.png
scr-004.png
scr-001.png scr-002.png scr-003.png scr-004.png

無事に取得できました。


✅PDFに出力したい

スクリーンショットでは ページの一部だけのため、本当は PDF 出力したい(PDFとして書き出す...)。

次回、PDF出力版のスクリプトを書きます。


参考

  • screencapture マニュアル
    
    SCREENCAPTURE(1)            General Commands Manual           SCREENCAPTURE(1)
    
    NAME
         screencapture – capture images from the screen and save them to a file or
         the clipboard
    
    SYNOPSIS
         screencapture [-SWCTMPcimswxto] file
    
    DESCRIPTION
         The screencapture utility is not very well documented to date.  A list of
         options follows.
    
         -c      Force screen capture to go to the clipboard.
    
         -b      Capture Touch Bar, only works in non-interactive modes.
    
         -C      Capture the cursor as well as the screen.  Only allowed in non-
                 interactive modes.
    
         -d      Display errors to the user graphically.
    
         -i      Capture screen interactively, by selection or window.  The
                 control key will cause the screenshot to go to the clipboard.
                 The space key will toggle between mouse selection and window
                 selection modes.  The escape key will cancel the interactive
                 screenshot.
    
         -m      Only capture the main monitor, undefined if -i is set.
    
         -D      <display> Screen capture or record from the display specified. 1
                 is main, 2 secondary, etc
    
         -o      In window capture mode, do not capture the shadow of the window.
    
         -p      Screen capture will use the default settings for capture. The
                 files argument will be ignored.
    
         -M      Open the taken picture in a new Mail message.
    
         -P      Open the taken picture in a Preview window or QuickTime Player if
                 video.
    
         -B      <bundleid> Open in the app matching bundleid.
    
         -s      Only allow mouse selection mode.
    
         -S      In window capture mode, capture the screen instead of the window.
    
         -J      <style> Sets the starting style of interfactive capture
                 "selection","window","video".
    
         -t      <format> Image format to create, default is png (other options
                 include pdf, jpg, tiff and other formats).
    
         -T      <seconds> Take the picture after a delay of <seconds>, default is 5.
    
         -w      Only allow window selection mode.
    
         -W      Start interaction in window selection mode.
    
         -x      Do not play sounds.
    
         -a      Do not capture attached windows.
    
         -r      Do not add screen dpi meta data to captured file.
    
         -l      <windowid> Captures the window with windowid.
    
         -R      <rectangle> Capture rectangle using format x,y,width,height.
    
         -v      Capture video recording of the screen.
    
         -V      <seconds> Capture video recording of the screen for the specified
                 seconds.
    
         -G      <id> Captures audio during a video recording using audio source
                 specified by id.
    
         -g      Captures audio during a video recording using default input.
    
         -k      Show clicks in video recordings.
    
         -U      Show interactive toolbar in interactive mode.
    
         -u      Present UI after screencapture is complete. Files passed to
                 commandline will be ignored.
    
         files   where to save the screen capture, 1 file per screen
    
    BUGS
         Better documentation is needed for this utility.
    
    SECURITY CONSIDERATIONS
         To capture screen content while logged in via ssh, you must launch
         screencapture in the same mach bootstrap hierarchy as loginwindow:
    
         PID=pid of loginwindow
         sudo launchctl bsexec $PID screencapture [options]
    
    HISTORY
         A screencapture utility first appeared in Mac OS X v10.2.
    
    Mac OS                           June 16, 2004                          Mac OS
    




以上

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?