【问题标题】:Capturing Screenshot and saving to a Document with Python background script使用 Python 后台脚本捕获屏幕截图并保存到文档
【发布时间】:2020-08-08 12:10:19
【问题描述】:

我正在做一些测试活动,这需要我捕获应用程序/数据库等的屏幕截图并将其保存到文档中。整个活动有50多张截图。 Python中有没有一种方法可以通过Windows快捷键(例如CTRL ALT shift C)截屏并将图像附加到文档文件中。我相信 python 程序应该像 Unix 中的 nohup 一样在后台运行 有人可以指导我吗?

【问题讨论】:

    标签: python testing qa


    【解决方案1】:

    要使用热键在 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" # main document
    hotkey = 'ctrl+shift+q'  # use this combination anytime while 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 screenshot, active app
            # shot = pyautogui.screenshot() # take screenshot full screen
            shot.save(shotfile) # save screenshot
            
            # append to document. Doc must exist.
            doc = Document(docxfile) # open document
            doc.add_picture(shotfile, width=Inches(7))  # add image, 7 inches wide
            doc.save(docxfile)  # update document
            print ('Done capture.')
        except Exception as e:  # allow 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
    

    【讨论】:

    • 没问题。请确认答案以将其从“无答案”列表中删除。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多