注:pyautogui 只是能够控制鼠标和键盘事件,并不能提取屏幕中的文本信息

# 依赖安装

pip install pyautogui

# 快速上手

import pyautogui
# 屏幕大小
print(pyautogui.size())
# 获取鼠标当前位置
print(pyautogui.position())
# 判断坐标是否在屏幕内 (x 的取值范围是 [0, 宽度分辨率 - 1],y 的取值范围是 [0, 高度分辨率 - 1])
print(pyautogui.onScreen(1920, 100))

# 鼠标控制

# 保存屏幕尺寸
screenX, screenY = pyautogui.size()
# 绝对位置移动,移动到屏幕中央,鼠标移动过度时间 duration 为 1 秒
pyautogui.moveTo(screenX / 2, screenY / 2, duration=1)
# 相对位置移动,向右移动 100、向上移动 200,移动过度时间 duration 为 0.5 秒
pyautogui.moveRel(100, 0, duration=0.5)
pyautogui.moveRel(0, -200, duration=0.5)
pyautogui.moveRel(100, -200, duration=0.5)
# 不指定 x、y,在当前位置点击一下右键
pyautogui.click(button='right')
# 移动至(100,100)点击 3 次左键,点击间隔 0.1s,鼠标移动过度时间 duration 为 0.5s
pyautogui.click(100, 100, clicks=3, interval=0.1, duration=0.5)
# 移动至 (100,100) 点击 2 次右键,点击间隔 0.5s,鼠标移动过渡时间 0.2 秒
pyautogui.click(100, 100, button='right', clicks=2, interval=0.5, duration=0.2)
# 将鼠标从当前位置拖至屏幕中心,默认点击左键
pyautogui.dragTo(screenX / 2, screenY / 2)
# 将鼠标从当前位置向左 100 像素、向右 200 像素拖动,过渡时间 0.5 秒,指定点击右键
pyautogui.dragRel(-100, 200, duration=0.5, button='right')

# 键盘控制

# 键名用字符串表示,支持的所有键名,存在 pyautogui.KEYBOARD_KEYS 变量中,包括 26 个字母、数字、符号、F1~F20、方向等等所有按键
# 按字母 A 键,字母支持大小写
pyautogui.typewrite('A')
pyautogui.typewrite('hello, PyAutoGUI!\n')
# 传入键名列表(按键 p、按键 y、空格),按键之间间隔 0.1 秒(默认 0)
pyautogui.press(['p', 'y', ' '], interval=0.1)
pyautogui.typewrite(['capslock', 'p', 'y'], interval=0.1)
# hotkey 屏蔽了需要反复 keyDown、keyUp 的细节,参数是任意个键名,而非列表
pyautogui.hotkey('shift', 'shift', 'esc', interval=0.1)

# 消息窗口

pyautogui.alert(text='警告', title='PyAutoGUI消息框', button='OK')
pyautogui.confirm(text='请选择', title='PyAutoGUI消息框', buttons=['1', '2', '3'])
txt = pyautogui.prompt(text='请输入', title='PyAutoGUI消息框', default='请输入')
pwd = pyautogui.password(text='输入密码', title='PyAutoGUI消息框', default='', mask='*')

# 截图

# imageFilename 参数,截图要保存的文件全路径名,默认 `None`,不保存;
# region 参数,截图区域,由左上角坐标、宽度、高度 4 个值确定,如果指定区域超出了屏幕范围,超出部分会被黑色填充,默认 `None`, 截全屏
pyautogui.screenshot('shot.png', region=(1000, 600, 600, 400))

# 通过按钮图片定位按钮位置

前提:需要安装 opencv-python 依赖

import pyautogui
import cv2
import numpy as np
def get_img_button_position(img_path):
    """
    获取按钮图片的在屏幕中的位置
    :param img_path: 按钮图片路径
    :return: 按钮图片的中心位置
    """
    template = cv2.imread(img_path, 0)
    w, h = template.shape[::-1]
    # 截取屏幕图片
    screenshot = pyautogui.screenshot()
    screenshot_np = np.array(screenshot)
    screenshot_gray = cv2.cvtColor(screenshot_np, cv2.COLOR_BGR2GRAY)
    # 使用模板匹配找到按钮位置
    res = cv2.matchTemplate(screenshot_gray, template, cv2.TM_CCOEFF_NORMED)
    threshold = 0.8  # 你可以调整这个阈值来找到最佳匹配
    loc = np.where(res >= threshold)
    # 获取匹配区域的左上角坐标
    for pt in zip(*loc[::-1]):
        cv2.rectangle(screenshot_np, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
    # 显示结果图片
    # cv2.imshow('Detected', screenshot_np)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    button_center = (pt[0] + w // 2, pt[1] + h // 2)
    print(f"Button center: {button_center}")
    return button_center
# 通过图片定位对象位置
button_position = get_img_button_position('./data/kais.png')
pyautogui.moveTo(*button_position, duration=0.5)  # 移动鼠标
pyautogui.click(clicks=1)  # 左键点击

# 获取当前鼠标位置技巧

运行以下代码,将光标固定在 input 输入后面,再将鼠标移动到目标点,回车,控制台就会输出目标的坐标

for i in range(10):
    input("当前坐标:")
    print(pyautogui.position())