Search code examples
pythonpython-3.xmacospython-imaging-libraryscreenshot

Get a screenshot of a specific window with pillow on macos


I am trying to take screenshots of a specific chrome window on my mac with python, (not the full screen, but just the chrome window)

I've seen some solutions for Windows, but none for mac yet. I think this is possible with pillow, but I'm not sure.


Solution

  • You can grab a specific region of the screen with PIL's ImageGrab() if you specify a bounding box. So, to get a 640x480 rectangle at top-left corner of screen, you can use:

    from PIL import ImageGrab
    
    # Grab top-left rectangle with size 640px wide by 480px tall
    img = ImageGrab.grab(bbox=(0, 0, 639, 479))
    

    So, one possibility might be to position your Chrome window to some known location, e.g. top-left corner and then capture.

    You should be able to do that using Applescript adapted from my answer here invoking it using subprocess().


    You may be able to use mss but I haven't tried it.


    You may be able adapt my answer here.


    You may be able to use locateOnScreen() from pyautogui to find something you know/expect to be in your Chrome window.