Python獲取進程並實現自動化操作

Python · 08-21 · 279 人浏览

獲取應用程式進程並識別圖片獲取坐標,最後滑鼠點擊,還有按鍵操作
首先安裝庫

pip install psutil mss opencv-python pyautogui numpy

然後

import psutil
import mss
import cv2
import numpy as np
import pyautogui
import time



import keyboard
import time

# 等待5秒钟,方便你切换到要操作的窗口
time.sleep(5)

# 按键
keyboard.press_and_release('2')


# 游戏进程名称
TARGET_PROCESS_NAME = "PokeMMO.exe"  # 替换为你的游戏进程名
# 要识别的图片路径
TARGET_IMAGE_PATH = "image/login.png"  # 替换为你的目标图片路径

def find_process_by_name(process_name):
    """查找指定名称的进程"""
    for process in psutil.process_iter(attrs=['pid', 'name']):
        if process.info['name'].lower() == process_name.lower():
            return process.info['pid']
    return None

def capture_screen(bbox=None):
    """截取屏幕"""
    with mss.mss() as sct:
        return np.array(sct.grab(bbox or sct.monitors[1]))

def find_image_on_screen(screen, template):
    """在截图中寻找指定图片"""
    result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)
    threshold = 0.8  # 设定匹配阈值
    loc = np.where(result >= threshold)

    points = []
    for pt in zip(*loc[::-1]):
        points.append(pt)
    return points

def main():
    # 加载目标图片
    target_image = cv2.imread(TARGET_IMAGE_PATH)
    h, w, _ = target_image.shape

    while True:
        # 查找游戏进程
        pid = find_process_by_name(TARGET_PROCESS_NAME)
        if pid is None:
            print("未找到游戏进程,等待...")
            time.sleep(5)
            continue

        # 截取屏幕
        screen = capture_screen()
        screen_rgb = cv2.cvtColor(screen, cv2.COLOR_BGRA2BGR)

        # 查找目标图片
        points = find_image_on_screen(screen_rgb, target_image)

        if points:
            for pt in points:
                # 计算点击位置
                click_x = pt[0] + w // 2
                click_y = pt[1] + h // 2
                pyautogui.click(click_x, click_y)  # 自动点击
                print(f"点击位置: ({click_x}, {click_y})")
                time.sleep(1)  # 点击后等待1秒
        else:
            print("未找到目标图片,重试...")

        time.sleep(1)  # 每秒执行一次

if __name__ == "__main__":
    main()
本站立足于美利堅合衆國,請讀者自覺遵守當地法律!如有違規,本站不承擔任何法律責任! This site is based in the United States of America, readers are requested to abide by local laws! If there are any violations, this site does not bear any legal responsibility! Theme Jasmine by Kent Liao