使用 Python 在 Windows 上截屏?
- 2025-02-27 09:06:00
- admin 原创
- 60
问题描述:
我正在创建一个 Beta 测试人员报告模块,以便他们可以发送对我的软件的评论,但我希望可以选择在报告中包含屏幕截图。如何在 Windows 上使用 Python 截取屏幕截图?我在 Linux 上找到了几个示例,但在 Windows 上运气不佳。
解决方案 1:
另一种非常快速的方法是MSS模块。它与其他解决方案的不同之处在于它仅使用ctypes
标准模块,因此不需要很大的依赖性。它独立于操作系统,使用起来很简单:
from mss import mss
with mss() as sct:
sct.shot()
只需找到screenshot.png
包含第一个显示器屏幕截图的文件即可。有很多可能的自定义,您可以使用ScreenShot
对象和 OpenCV/Numpy/PIL/等进行操作。
解决方案 2:
值得注意的是,ImageGrab 仅适用于 MSWindows。
对于跨平台兼容性,最好使用 wxPython 库。http
://wiki.wxpython.org/WorkingWithImages#A_Flexible_Screen_Capture_App
import wx
app = wx.App() # Need to create an App instance before doing anything
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.Bitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem # Release bitmap
bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
解决方案 3:
您可以使用 ImageGrab 模块。ImageGrab 适用于 Windows 和 macOS,您需要PIL (Pillow) 才能使用它。这里有一个小例子:
from PIL import ImageGrab
snapshot = ImageGrab.grab()
save_path = "C:\\Users\\YourUser\\Desktop\\MySnapshot.jpg"
snapshot.save(save_path)
解决方案 4:
对于 pyautogui 用户:
import pyautogui
screenshot = pyautogui.screenshot()
解决方案 5:
截屏的一个简单方法是通过 Pygame。
pygame.image.save(Surface, filename)
其中“Surface”是您要截屏的表面,“filename”是保存图像的文件路径、名称和类型。
您可以导出为 BMP、TGA、PNG 或 JPEG。从 Pygame 1.8 开始,PNG 和 JPEG 也可以使用。
如果没有指定文件扩展名,它将默认为 .TGA 文件。
您甚至可以使用“os”库保存到特定的文件目录。
举个例子:
import os
import pygame
surface = pygame.display.set_mode((100, 100), 0, 32)
surface.fill((255, 255, 255))
pygame.draw.circle(surface, (0, 0, 0), (10, 10), 15, 0)
pygame.display.update()
pygame.image.save(surface, os.path.expanduser("~/Desktop/pic.png"))
这会将“表面”Surface 上的所有内容保存到用户的桌面,如 pic.png
解决方案 6:
如果您想要捕捉特定正在运行的 Windows 应用程序,您必须通过循环遍历系统中所有打开的窗口来获取句柄。
如果您可以从 Python 脚本打开此应用程序,那就更容易了。然后您可以将进程 pid 转换为窗口句柄。
另一个挑战是捕捉在特定显示器上运行的应用程序。我有 3 个显示器系统,我必须弄清楚如何捕捉显示器 2 和 3。
此示例将拍摄多个应用程序快照并将其保存到 JPEG 文件中。
import wx
print(wx.version())
app=wx.App() # Need to create an App instance before doing anything
dc=wx.Display.GetCount()
print(dc)
#e(0)
displays = (wx.Display(i) for i in range(wx.Display.GetCount()))
sizes = [display.GetGeometry().GetSize() for display in displays]
for (i,s) in enumerate(sizes):
print("Monitor{} size is {}".format(i,s))
screen = wx.ScreenDC()
#pprint(dir(screen))
size = screen.GetSize()
print("Width = {}".format(size[0]))
print("Heigh = {}".format(size[1]))
width=size[0]
height=size[1]
x,y,w,h =putty_rect
bmp = wx.Bitmap(w,h)
mem = wx.MemoryDC(bmp)
for i in range(98):
if 1:
#1-st display:
#pprint(putty_rect)
#e(0)
mem.Blit(-x,-y,w+x,h+y, screen, 0,0)
if 0:
#2-nd display:
mem.Blit(0, 0, x,y, screen, width,0)
#e(0)
if 0:
#3-rd display:
mem.Blit(0, 0, width, height, screen, width*2,0)
bmp.SaveFile(os.path.join(home,"image_%s.jpg" % i), wx.BITMAP_TYPE_JPEG)
print (i)
sleep(0.2)
del mem
详细信息请见此处
解决方案 7:
首先,使用 pip3 安装 PrtSc 库。
import PrtSc.PrtSc as Screen
screenshot=PrtSc.PrtSc(True,'filename.png')
解决方案 8:
我遇到了一些 Python 截图问题,到目前为止,使用 shot-scraper 已经获得了最好的结果。
pip install shot-scraper
然后安装Playwright
shot-scraper install
截屏:
shot-scraper <URL>
详细信息和代码位于 GitHub 存储库中。
解决方案 9:
另一个解决方案是使用 PowerShell 脚本作为与 Windows 相关的 PowerShell,因此您可以从 python 运行 PowerShell 脚本:
来自 rogerdpack 的这个答案
PowerShell 截屏并保存在提供的路径内
[Reflection.Assembly]::LoadWithPartialName("System.Drawing")
function screenshot([Drawing.Rectangle]$bounds, $path) {
$bmp = New-Object Drawing.Bitmap $bounds.width, $bounds.height
$graphics = [Drawing.Graphics]::FromImage($bmp)
$graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.size)
$bmp.Save($path)
$graphics.Dispose()
$bmp.Dispose()
}
$bounds = [Drawing.Rectangle]::FromLTRB(0, 0, 1000, 900)
screenshot $bounds "C:screenshot.png" # change path to somewhere writable
请注意,PowerShell 执行将默认被禁用,因此您可以使用 PowerShell 中的此行来启用它(请确保在完成后再次将其禁用以确保安全(通常这是为了执行 ps 文件)
Set-ExecutionPolicy RemoteSigned
此 python 代码用于从 python 运行 powershell 脚本
completed = subprocess.run(["powershell", "here add the previous powershell script that will take screenshot", cmd], capture_output=True)
# do something if success or failed
if completed.returncode != 0:
print("An error occured: %s", hello_info.stderr)
else:
print("Hello command executed successfully!")
扫码咨询,免费领取项目管理大礼包!