Take a Screenshot using Python

How to Take a Screenshot using Python

Take a Screenshot using Python

Screenshots are a great way to capture visual content on your computer screen. Python provides an easy way to take screenshots of your computer screen using the pyautogui library in python . In this article, we will walk through how to take a screenshot using Python Programming.

How to Take a Screenshot using Python

Steps to Take a Screenshot using Python

Step 1: Install the pyautogui package

To install the pyautogui library, you can use pip. Open up your terminal and type the following command:

pip install pyautogui

Step 2: Import the following  library .

import os
import argparse
import pyautogui
import time

step 3: Copy the code for the take a screenshot using  Python, which I provided Below in this article, and save it in a file named “main.py” (or any other name you prefer).

  1.  Run this  python file  main.py to take screenshot.

complete code 👇👇

import os
import argparse
import pyautogui
import time

parser = argparse.ArgumentParser()

parser.add_argument("-p", "--path", help="absolute path to store screenshot.", default=r"./images")
parser.add_argument("-t", "--type", help="h (in hour) or m (in minutes) or s (in seconds)", default='h')
parser.add_argument("-f", "--frequency", help="frequency for taking screenshot per h/m/s.", default=1, type=int)

args = parser.parse_args()


if args.type == 'h':
    sec = 60 * 60 / args.frequency
elif args.type == 'm':
    sec = 60 / args.frequency

if sec < 1.:
    sec = 1.
    

if os.path.isdir(args.path) != True:
    os.mkdir(args.path)


try:
    while True:
        t = time.localtime()
        current_time = time.strftime("%H_%M_%S", t)
        file = current_time + ".jpg"
        image = pyautogui.screenshot(os.path.join(args.path,file))
        print(f"{file} saved successfully.\n")
        time.sleep(sec)
        
except KeyboardInterrupt:
    print("End of script by user interrupt")

You should get a .png file in the same directory as your Python code.

Below is an example of what my screenshot looks like:👇👇How to Take a Screenshot using Python

Conclusion

Taking screenshots using Python is an easy and useful way to capture visual content. With the  pyautogui library, you can easily capture screenshots of your computer screen and save them to files. So, go ahead and start capturing your screen with Python!

Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my python articles.

 

Build A Flames Game in Python | Python Project

Check Leap Year using Python Programming

Build A Currency Converter in Python

 



Leave a Reply