python - 使用 Python 后台脚本捕获屏幕截图并保存到文档

标签 python screenshot

我正在做一些测试事件,这需要我捕获应用程序、数据库系统等的屏幕截图并将其保存到文档中。

整个事件有超过50张截图。 Python中有没有一种方法可以使用Windows快捷键截取屏幕截图(例如,Ctrl + Alt + Shift + < kbd>C)并将图像附加到文档文件中?

我相信Python程序应该在后台运行,例如nohup在 Unix 中。

最佳答案

用于将屏幕截图存储在 Word 中使用热键,您可以使用库的组合。

  • 使用win32gui打开Word
  • 使用python-docx更新文档并保存
  • 使用PyAutoGUI 进行屏幕捕获
  • 使用键盘监听热键

要使该脚本正常工作,您需要在运行该脚本之前创建 Word 文档。

# Need these libraries
# pip install keyboard
# pip install PyAutoGUI
# pip install python-docx
# pip install win32gui

import keyboard
import pyautogui
from docx import Document
from docx.shared import Inches
import win32gui
from PIL import ImageGrab

shotfile = "C:/tmp/shot.png"  # Temporary image storage
docxfile = "C:/tmp/shots.docx" # The main document
hotkey = 'ctrl+shift+q'  # Use this combination anytime while the script is running

def do_cap():
    try:
        print ('Storing capture...')

        hwnd = win32gui.GetForegroundWindow()  # Active window
        bbox = win32gui.GetWindowRect(hwnd)  # Bounding rectangle

        # capture screen
        shot = pyautogui.screenshot(region=bbox) # Take a screenshot, active app
        # shot = pyautogui.screenshot() # Take a screenshot full screen
        shot.save(shotfile) # Save the screenshot

        # Append to the document. Doc must exist.
        doc = Document(docxfile) # Open the document
        doc.add_picture(shotfile, width=Inches(7))  # Add the image, 7 inches wide
        doc.save(docxfile)  # Update the document
        print ('Done capture.')
    except Exception as e:  # Allow the program to keep running
        print("Capture Error:", e)

keyboard.add_hotkey(hotkey, do_cap)  # Set hot keys

print("Started. Waiting for", hotkey)

keyboard.wait()   # Block forever

关于python - 使用 Python 后台脚本捕获屏幕截图并保存到文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63315215/

相关文章:

python - 是否可以从同一个 github 存储库运行 2 个单独的 .travis.yml 文件

python - 在 Flask 中使用 socketio.on() 渲染一个新模板

python - 如何命名仅包含类定义的Python文件?

ios - 在拍摄屏幕截图之前隐藏 View 中的元素

java - 问题: Shutterbug Screenshot create a new folder for each screenshot instead of keeping them in 1 folder

java - 筛选并上传 Java 类在本地工作,但不能在线工作。没有任何错误。怎么了?

iphone - Xcode 管理器屏幕捕获问题

python - Seaborn tsplot 在 x 轴上更改标签

python - Pandas:创建一列,其中行等于另一列中下面的行

android - 当应用程序禁用它时如何在Android上截取屏幕截图?