How to use ImageGrab.grab() In Python

The pillow (PIL) library has an ImageGrab module that can be used to copy the contents of the screen or the clipboard to a PIL image memory.

Installing PIllow

pip install Pillow

grab(): The grab() method is used to take a screenshot of the screen. The pixels inside the bounding box are returned as an “RGBA” on macOS, or an “RGB” image otherwise. If the bounding box is omitted, the entire screen is copied.

So now to take screenshots at random time intervals we will make use of grab() and sleep() and random() methods. the grab() will be used to take snapshots, randint() and sleep() will be used to create delay at random time intervals.

Syntax: PIL.ImageGrab.grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None)

Parameters:

  • bbox – What region to copy. Default is the entire screen
  • Includes layered windows – boolean value
  • all_screens –Capture all monitors. Windows OS only.

Return: an image

Example:

In the above code, a random delay was generated between 1 to 5 seconds before taking a screenshot using grab() method. generate a random number between 1 to 5, and create a time delay using the sleep() method. The screenshots will be saved in the exact location of the program with the file name as current time.

  • Import PIL, random, and time libraries.
  • Take a screenshot using the grab() method and wait for sometime
  • Create the random delay using randint() method and sleep().
  • save the screenshots with the name as the current time.

Python3




# importing ImageGrab class
from PIL import ImageGrab
  
# importing random module
import random
  
# importing time module
import time
  
# Running the while loop for infinite time
while True:
    # generating a random number between
    # 1 to 5 , which will represent the 
    # time delay
    random_time = random.randint(1, 5)
  
    # create a time delay using the sleep() 
    # method
    time.sleep(random_time)
  
    # Take the screenshot using grab()
    # method
    snapshot = ImageGrab.grab()
  
    # Save the screenshot shot using current time
    # as file name.
    file_name = str(time.time())+".png"
    snapshot.save(file_name)


Output:

 

Take Screenshots at Random Intervals with Python

In this article, we will learn how to take screenshots at Random Intervals with Python.

Similar Reads

Method 1: Using pyautogui.screenshot()

pyautogui: The pyautogui library provides the screenshot() method, The screenshot() method is used to take a screenshot. We will use the random library and sleep() method to take screenshots at Random Intervals....

Method 2: Using ImageGrab.grab()

...

Method 3: Using shot()  from MSS module

The pillow (PIL) library has an ImageGrab module that can be used to copy the contents of the screen or the clipboard to a PIL image memory....