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

问题描述 投票:0回答:3

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

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

我相信Python程序应该在后台运行,就像Unix中的nohup

python screenshot
3个回答
2
投票

要使用热键将屏幕截图存储在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

1
投票

相同的代码只需进行一些小的更改即可工作。 感谢您提供上面的代码。然而,面临一些挑战并解决了一些问题,下面的代码工作得很好。屏幕截图带有时间戳。

hotkey = 'win+prtscn' # use this combination anytime while script is running

全屏截取带有时间戳的屏幕截图

shot = pyautogui.screenshot() # to take screenshot full screen with timestamp

附加到文档。文档必须存在。

    docxfile = r'C:\tmp\shots.docx' # main document ADDED THIS STATEMENT

只有使用该代码添加或更改的上述语句才能完美运行。 也可以使用热键 Windows 徽标以及打印屏幕。当代码处于调试模式时

win+prntscrn
会将图像存储在代码中指定的位置以及默认位置图片截图文件夹中

停止调试模式后,win+prntscrn 将仅将图像存储在默认位置的屏幕截图文件夹中。

但是,在停止调试模式后使用热键

cntrl+shift+q
时,shot.png 图像将具有没有时间戳的图像。 在调试模式下,使用上述热键时
shot.png
将显示图像和时间戳。


1
投票

创建新的空白文档:

except:
    document = docx.Document()
    #document.save('CKS1.docx')
    document.save('C:/tmp/CKS0.docx')
    print ('Doc created.')     # Doc created

    #doc1 = Document('CKS0.docx') # open document
    #doc1.add_picture(shotfile, width=Inches(7))  # add image, 7 inches wide
    #doc1.save('CKS0.docx')  # update document
    print ('Done capture.')
    print("Previous file was corrupted or didn't exist - new file was created.")
© www.soinside.com 2019 - 2024. All rights reserved.