Python如何做到动态捕捉屏幕内容?

当屏幕上出现了需要捕捉的图片元素,则可以获取到并作出相应。

比如说监控聊天窗口界面,当有人发了任意消息,则立刻可以作出相应(比如说截个图啥的)

如何在指定位置截图这一部分我正在学习....可是如何动态的捕捉屏幕的内容却找不到资料。

目前的想法是,循环执行一段截取固定区域的代码,然后把截取的图片和最初预设的图片进行比较,当图片相似则不作任何操作,当截取的图片发生变化则保存截取的图片。只是感觉这样貌似很麻烦...而且循环设置时间过短的话会不会对机器的负担比较大...?

希望各位大神们能不吝赐教,谢谢。

因为屏幕上的文字都是通过调用api函数(windows的系统调用例程)的方式绘制到屏幕上的,所以可以通过api函数拦截的方法来捕捉写到屏幕上的文字。

http://download.csdn.net/download/caozhy/9959220 逆向工程核心原理(含源代码) 这本书的第32章给出了一个如何通过拦截windows api实现让计算器程序输出中文的结果

图片说明

配套的源代码是一个通用的,可以在python直接调用


import pandas as pd
import uiautomation as auto
import win32clipboard
import pyautogui
import pyperclip
import os
import time
from ctypes import *
def open_wechat():
    '检测微信界面是否开启,如果没有打开微信界面'
    wechatWindow = auto.WindowControl(searchDepth=1, Name="微信", ClassName='WeChatMainWndForPC')
    if not wechatWindow.Exists(1):
        print('正在打开微信窗口')
        # shellTray =auto.Control()
        file = os.popen(r'D:/wexin/WeChat/WeChat.exe')
        # print(file)
        file.close()
    else:
        wechatWindow.SetActive()
        # print(wechatWindow.SetActive())

def get_xiaoxi():
    '识别微信聊天框最后一句消息,如果消息为指令,则执行指令'
    open_wechat()
    wechatWindow = auto.WindowControl(searchDepth=1, Name="微信", ClassName='WeChatMainWndForPC')
    # wechatWindow.SetTopmost(False)
    # wechatWindow.SetTopmost()
    messages = wechatWindow.ListControl(Name='消息')
    result = []
    time = pd.NA
    for message in messages.GetChildren():
        content = message.Name
        if content in ["查看更多消息", "以下为新消息"]:
            continue
        details = message.GetChildren()[0].GetChildren()
        if len(details) == 0:
            time = content
            continue
        nickname, detail, me = details
        name = nickname.Name
        if me.Name:
            name = me.Name

        link_all = pd.NA
        if not (content == "[图片]" or content.startswith("[语音]")):
            details = detail.GetChildren()
            if len(details) == 0:
                continue
            detail = details[-1].GetChildren()[0].GetChildren()[0].GetChildren()[0]
            details = detail.GetChildren()

            if len(details) != 0:
                link_title = details[0].Name
                link_content = details[1].Name
                content += f"{link_title}\n{link_content}"
        #     print(time, name, content)
        result.append((time, name, content.strip()))

    df = pd.DataFrame(result, columns=["时间", "昵称", "内容"])
    return df


def if_kl():
    df=get_xiaoxi()
    print(df['内容'].values[-1])
    if df['内容'].values[-1] == '你好':
        pyautogui.PAUSE = 0.5
        open_wechat()
        pyperclip.copy('你好呀')
        pyautogui.hotkey('ctrl', 'v')
        pyautogui.hotkey('enter')
    if df['内容'].values[-1] == '哈哈哈':
        pyautogui.PAUSE = 0.5
        open_wechat()
        pyperclip.copy('笑个嘚')
        pyautogui.hotkey('ctrl', 'v')
        pyautogui.hotkey('enter')

def get_newest_file(file_path):
    dir_list = os.listdir(file_path)
    if not dir_list:
        return

    else:
        # 注意,这里使用lambda表达式,将文件按照最后修改时间顺序升序排列,
        # sorted的参数reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)
        # os.path.getmtime() 函数是获取文件最后修改时间
        # os.path.getctime() 函数是获取文件最后创建时间
        dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x)), reverse=True)
        for aa in dir_list:
            if aa.endswith('.xlsx') and aa.startswith('广西机顶盒软探针指标分析报告(分析完成版)'):
                file_out = aa
                break
        return file_out


class DROPFILES(Structure):
    _fields_ = [
        ("pFiles", c_uint),
        ("x", c_long),
        ("y", c_long),
        ("fNC", c_int),
        ("fWide", c_bool),
    ]

pDropFiles = DROPFILES()
pDropFiles.pFiles = sizeof(DROPFILES)
pDropFiles.fWide = True
matedata = bytes(pDropFiles)

# 复制到剪切板S
def setClipboardFiles(paths):
    '设置剪切板S'
    files = ("\0".join(paths)).replace("/", "\\")
    data = files.encode("U16")[2:] + b"\0\0"
    win32clipboard.OpenClipboard()
    try:
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardData(win32clipboard.CF_HDROP, matedata + data)
    finally:
        win32clipboard.CloseClipboard()

def setClipboardFile(file):
    '设置剪切板'
    setClipboardFiles([file])

def send():
    ########### 注意修改发送键
    pyautogui.hotkey('enter')


def wechat_tishi():
    pyautogui.PAUSE = 0.5
    open_wechat()
    pyperclip.copy('每5秒钟接收一次最后消息')
    pyautogui.hotkey('ctrl', 'v')
    pyautogui.hotkey('enter')

if __name__ == '__main__':
    a=0
    while a<5:
        a=a+1
        # wechat_tishi()
        time.sleep(5)
        if_kl()

Python只能截屏。没有能力做动态捕获。需要显卡驱动层面

https://blog.csdn.net/u012577474/article/details/106319306/