In this Python tutorial, we will learn about Python Screen Capture. Also, we will cover these topics.
- Python Screen Capture
- Python Screen Capture Specific Window
- Python Screen Capture Video
- Python Screen Capture OpenCV
- Python Screen Capture Library
- Python Screen Capture Fast
- Python Screen Capture Website
- Python Screen Capture Windows
Python Screen Capture
Python is a programming language that is used to develop all kinds of applications whether desktop-based or web-based. It is used for advanced purposes like data processing, machine learning, and many more.
- Python is rich with various useful libraries that allows you to create software of your own choice in less time.
- In this section, we will learn about Python Screen Capture. We will see how to take a screenshot of the window using python.
- Using pyautogui module in python we can take screenshot of the window and store it in a desired location.
Installation of pyautogui module on windows
We assume, that you have installed pip on your system. Use the below code to install the pyautogui module on your windows machine.
pip install pyautogui
Installation of pyautogui module on Linux (Ubuntu)
While installing the python pyautogui module on Linux it is important to install scrot package in the Linux machine. Without Scrot, a Linux machine won’t capture the screen. Follow the below command to install scrot package on your Linux (Ubuntu) machine.
sudo apt-get install scrot
Once scrot is installed use the below command to install the pyautogui module in your Linux (Ubuntu) machine.
pip install pyautogui
Also, read: Python Number Guessing Game
Python Screen Capture Specific Window
In this section, we will learn how to capture a specific window screen in python.
- In the previous section, we have leaned how to install pyautogui module on your device. Now using that module we will learn how to capture specific window. Here capturing means screenshot (still image) of the window.
- Screenshot() method of pyautogui module can be used to capture the screen. Use the below code to initiate screenshot.
pyautogui.screenshot()
- Once screenshot is taken it is imporant to specific the place where you want ot save that file. In the below code, specify the path where you want to save the screenshot file.
pyautogui.screenshot().save(r'file_path/filename.png')
or
screenshot = pyautogui.screenshot()
screenshot.save(r'file_path/filename.png')
- Screenshot will be captured immedietly after running the program so you won’t get time to select specific screen.
- To fix that, you can delay the execution of code snippet by 5 or 10 seconds using sleep method of time module.
- Here is the implementation of python screen capture specific window.
Source Code:
In this code, we have used a python built-in time module to delay the screenshot process by 5 seconds. after 5 seconds this code snippet is run myScreenshot = pyautogui.screenshot()
and a screenshot has been captured. after that myScreenshot.save(r'https://i0.wp.com/pythonguides.com/home/master/Desktop/capture/screenshot.png')
this code has saved the screenshot file in the same destination.
Output:
In the below output, you can notice that we are trying to capture the calculator window. After the program is run we have 5 seconds to position the application window. After 5 seconds new file is created and it has the screenshot.
Read: Python Count Words in File
Python Screen Capture Video
In this section, we will learn how to capture a Screen Video using python.
- Video is the rendering of frames per seconds in such a way that viewer believe that they are watching a sequence of activity.
- Python Screen capturing video means we will record all the activities happening on the screen and this file can be accessed later.
- There three modules involved in the screen video recording process.
- pyautogui module is used to capture the images
- NumPy module creates an array of these images
- Using Opencv module these images are grouped together and coverted to video of any format.
- Use the below command to install opencv and numpy in your system.
pip install opencv-python
pip install numpy
Source Code:
In this code, four modules have been imported for different tasks. A Series of images have been captured using pyautogui module. These images are arranged in an array using numpy and then converted to a video using the python OpenCV module. We have added a delay using the time module.
import cv2
import numpy as np
import pyautogui
import time
SCREEN_SIZE = (1920, 1080)
fource = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.mp4', fource, 20.0, (SCREEN_SIZE))
fps =30
prev = 0
while True:
time_elapsed = time.time()-prev
img = pyautogui.screenshot()
if time_elapsed > 1.0/fps:
prev = time.time()
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
out.write(frame)
cv2.waitKey(10000)
Output:
In this output, Once you will execute the program it will start capturing the current window. Use ctrl + c
to terminate the process.
Read: If not condition in python
Python Screen Capture OpenCV
In this section, we will learn about Python Screen Capture using OpenCV. OpenCV is a python module used for image processing.
- Video is the rendering of frames per seconds in such a way that viewer believe that they are watching a sequence of activity.
- Python Screen capturing video means we will record all the activities happening on the screen and this file can be accessed later.
- There three modules involved in the screen video recording process.
- pyautogui module is used to capture the images
- NumPy module creates an array of these images
- Using Opencv module these images are grouped together and coverted to video of any format.
- Use the below command to install opencv and numpy in your system.
pip install opencv-python
pip install numpy
Source Code:
In this code, four modules have been imported for different tasks. A Series of images have been captured using pyautogui module. These images are arranged in an array using numpy and then converted to a video using the python OpenCV module. We have added a delay using the time module.
import cv2
import numpy as np
import pyautogui
import time
SCREEN_SIZE = (1920, 1080)
fource = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.mp4', fource, 20.0, (SCREEN_SIZE))
fps =30
prev = 0
while True:
time_elapsed = time.time()-prev
img = pyautogui.screenshot()
if time_elapsed > 1.0/fps:
prev = time.time()
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
out.write(frame)
cv2.waitKey(10000)
Output:
In this output, Once you will execute the program it will start capturing the current window. Use ctrl + c
to terminate the process.
Read: Remove non-ASCII characters Python
Python Screen Capture Library
In this section, we will explore the Python Screen Capture Library. We look for the most popular libraries used for capturing screenshots and videos in Python.
- pyautogui
- opencv
- ImageGrab
1. pyautogui
Pyautogui library in python is used to automate the interaction with other applications. Using screenshot() method of the pyautogui module we can capture the screenshot of the window. Follow the below command to install the python pyautogui module on your system. Since we are using pip so it will work on all the operating systems.
pip install pyautogui
2. OpenCV
Python OpenCV is an open-source library for computer vision, machine learning, and image processing. Using this module we can capture the video of the screen. OpenCV helps only in converting the files (still images) into video. pyautogui module is put on the loop and each image is recorded and using numpy we can create an array of these images. Now, this array can be converted to a video format using OpenCV. Follow the below command to install OpenCV on your system.
pip install opencv-python
3. ImageGrab
Using Python PIL.ImageGrab module we can capture the screenshot of the desired windows. It provides a wide variety of options like capturing specific parts of the window, capturing all the screens in case the user is using multiple screens.
Syntax:
Here is the syntax of PIL.ImageGrab.grab().
PIL.ImageGrab.grab(
bbox=None,
include_layered_windows=False,
all_screens=False,
xdisplay=None
)
- bbox: allows to select the region to copy. default is full screen.
- include_layered_windows: It includes all the layers but this feature works only on windows os.
- all_screens: incase user is using multiple monitors then use can capture all the monitors using this option. This works only on windows.
Read: How to create a list in Python
Python Screen Capture Fast
In this section, we will learn about Python Screen Capture Fast. We will learn how to quickly record the content on the screen.
- Recording screen video involves 3 major modules. OpenCV, Numpy and pyautogui in python.
- Using pyautogui we keep on capturing the frame untill the program is terminated. Then using numpy these images are set into an array. In the end, this array is converted to video format using python-opencv.
Source Code:
modules have been imported for different tasks. A Series of images have been captured using pyautogui module. These images are arranged in an array using numpy and then converted to a video using the python OpenCV module. We have added a delay using the time module.
import cv2
import numpy as np
import pyautogui
import time
SCREEN_SIZE = (1920, 1080)
fource = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.mp4', fource, 20.0, (SCREEN_SIZE))
fps =30
prev = 0
while True:
time_elapsed = time.time()-prev
img = pyautogui.screenshot()
if time_elapsed > 1.0/fps:
prev = time.time()
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
out.write(frame)
cv2.waitKey(1000)
Output:
In this output, the program has started recording the current window.
Read: Remove Unicode characters in python
Python Screen Capture Website
In this section, we will learn how to take screenshots of websites using Python.
- Using Python Selenium module we can capture the screenshot of any website.
- Python Selenium is used to automate the browser using web drivers. In other words, we can regulate any activity on the browser without any human intervention.
- Python Selenium is the major tool used for automation and testing. Let’s say you want to test the form on website. Then using selenium you can provide all the instructions to reach that form page and then provide various set of inputs. Once the program is executed it will automatically open the browser, type the website name in the url box and will reach to the destination page and perform the activity.
- Use the below command to install selenium in your system.
pip install selenium
- Web drivers allows cross browser test. Each web browser (chrome, safari, firefox) has different web drivers.
- It is important to download the webdriver to make this process work. In our case, we are working on firefox so we will download firefox drivers. Click here to choose the web driver.
- Once web drivers are downloaded PATH needs to be set for them. Follow the below section to set up the PATH for web drivers.
Windows
If you are a windows user follow these instructions to set a path for web drivers.
- create directory
C:\bin
- Place the driver downloaded file inside
C:\bin
- use the below command to set the path.
setx PATH "%PATH%;C:\bin"
- restart the command prompt.
- verify the setup
chromedriver.exe -v
Linux or MacOs
If you are a Linux or Mac user then follow these instructions to set the PATH for the web driver.
- Extract the .tar.gz file usin the following command. Please note that file name or version may change in future.
tar -xf geckodriver-v0.30.0-linux64.tar.gz
- Move the geckodriver file to
/usr/local/bin
or/user/local/bin
. Please note that you will need root permission.
sudo mv geckodriver /usr/local/bin
Once you have completed all these processes then you can start writing the code. In our code, we have opened our website pythonguides.com and then captured the screenshot of it.
Source code:
In this source code, we have imported webdriver from selenium and to add some delay we have used the time module.
driver = webdriver.Firefox()
in this code, we have initialised the web driver. You will see an error i the incorrect path is set for the web driver.driver.get(url)
, using this code we are opening the website provided by the user.driver.get_screenshot_as_file("capture.png")
using this code we are capturing the screenshot of the website.
from selenium import webdriver
from time import sleep
website = 'https://www.pythonguides.com'
driver = webdriver.Firefox()
driver.get(website)
sleep(2)
driver.get_screenshot_as_file("capture.png")
Output:
In this output, you can see that website opens automatically after running the program. And after 2 seconds capture.png file is generated which is the screenshot of that website.
Read: Comment lines in Python
Python Screen Capture Windows
In this section, we will learn how to capture a screen using python. We will be using the ImageGrab method of the Pillow module.
- Python Pillow module adds image processing capabilities to the python interpreter.
- This library provides extensive file format support, an efficient internal representation, and powerful image processing capabilities.
- Pillow is represented with PIL and it has method ImageGrab using which we can capture the current widow using python.
- It captures window immedietly after running the program so in our example we have delayed this process by 5 seconds using python time module.
Source code:
In this code, we have used the ImageGrab module which belongs to Pillow or PIL module in Python. Using grab() method in ImageGrab module we can capture the screenshot of the current screen.
import PIL.ImageGrab
import time
time.sleep(5)
img = PIL.ImageGrab.grab()
img.show()
Output:
In this output, after running the code the program will give us 5 seconds after that it will capture the current window.
You may also like to read the following tutorials.
- Python dictionary append
- Python square a number
- Python Pretty Print JSON
- Python Dictionary Methods
- Python Addition Examples
In this tutorial, we have learned about Python Screen Capture. Also, we will cover these topics.
- Python Screen Capture
- Python Screen Capture Specific Window
- Python Screen Capture Video
- Python Screen Capture OpenCV
- Python Screen Capture Library
- Python Screen Capture Fast
- Python Screen Capture Website
- Python Screen Capture Windows
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.