默认 · January 18, 2023 0

Python: How to take a screenshot using pyautogui

Table of Content

To capture screenshots using Python, you can use the PIL (Python Imaging Library) module. The PIL module can be used to take screenshots of the current screen, a specific window, or a particular region. Here is an example of how to capture a screenshot of the entire screen:

import PIL
import PIL.ImageGrab
# capture the entire screen
img = PIL.ImageGrab.grab()
# save the image
img.save('screenshot.png')

Alternatively, you can use the PyAutoGUI module to capture a screenshot of the current screen.

PyAutoGUI is a cross-platform, automation module that works on Py 2 & 3. You can control the mouse and keyboard. You can also perform basic image recognition to automate tasks on a computer.
PyAutoGUI can take screenshots, save them to files. These features are provided by the PyScreeze module.

The Pillow module supports the functionality. OS X uses the screencapture command. Linux uses the scrot command. It can be installed by running the following command:sudo apt-get install scrot
To install PyAutoGUI, install the pyautogui package from PyPI by running pip install pyautogui (on macOS and Linux).

How to take a screenshot in Pyautogui?

You may use the following template to take a screenshot. Calling screenshot() will return an Image object . Passing a string of a filename will save the screenshot to a file.

import pyautogui
myScreenshot = pyautogui.screenshot()
myScreenshot.save(r'Path to save screenshot\file name.png')

Step 1: Install package

pip install pyautogui

Step 2: Capture the path to save the screenshot

Next, capture the full path where the screenshot will be saved.

Step 3: Take the screenshot

import pyautogui

myScreenshot = pyautogui.screenshot()
myScreenshot.save(r'Path to save screenshot\file name.png')

Screenshot will saved at your specified location.

%d bloggers like this: