PyAutoGUI 使用教程 —— 喜欢你就 Copy 一下

前 言


  • PyAutoGUI 是一个纯 Python 的 GUI 自动化工具,它可以让程序自动控制鼠标和键盘等一系列操作来达到自动化操作目的。

  • 使用 PyAutoGUI 脚本,在执行期间,应避免手动移动鼠标或进行键盘输入,以免干扰脚本的执行。

  • 全局暂停设置:通过设置全局变量 pyautogui.PAUSE = “秒” ,来每个延迟每个动作执行的暂停时间,以防止错误或干扰。

  • 自动防故障:将鼠标快速移到屏幕左上角,脚本会立即停止执行。通过设置全局变量 pyautogui.FAILSAFE = True 来启用。

主要功能(目录):

  1. 鼠标操作
    • 移动鼠标:包括绝对位置移动和相对位置移动,可以设置移动过渡时间。
    • 点击鼠标:包括单击、双击、右键点击、中键点击等,可以设置点击位置和点击次数。
    • 拖动鼠标:从当前位置按下鼠标,移动至目标位置再释放的过程。
    • 滚动鼠标滚轮:可以向上或向下滚动指定单位。
  2. 按键控制
    • 模拟按键输入:可以输入文本、按下并释放特定按键、组合键等。
    • 处理警告框和弹窗:可以模拟点击确认、取消等按钮。
  3. 屏幕操作
    • 截图:可以截取全屏或指定区域的屏幕,并保存为图片文件。
    • 图像识别:可以在屏幕上查找特定图像的位置,并进行点击等操作。
  4. 消息窗口
    • 可以显示消息框、警告框、确认框等,与用户进行交互。
  5. 练习用例
    • 获取鼠标在屏幕中的位置,并获取像素点 RGB 值。
    • 根据截图,光标自动移到相似的图像区。

安装方式:

  1. cmd 执行 pip install pyautogui -i https://pypi.tuna.tsinghua.edu.cn/simple # -i 可选清华源
  2. 下载 tar.gz 离线包,cmd 到解压目录执行 python setup.py install,官网链接 https://pypi.org/project/PyAutoGUI/#files

一、鼠标操作

import pyautogui as gui

# 屏幕坐标值(x, y): X值越大越靠右, Y值越大越靠下。原点(0, 0), 即: 屏幕最左上方
print(gui.position())               # 获取当前光标坐标
print(gui.size())                   # 获取屏幕分辨率
print(gui.onScreen(1921, 1081))     # 判断坐标值,是否在屏幕上
'''
>>> Point(x=1298, y=795)
>>> Size(width=1920, height=1080)   
>>> False
'''

# 1.鼠标移动:绝对坐标,相对坐标
gui.moveTo(100, 100, duration=0.25)  # 函数执行用时, 默认0.1s
gui.moveTo(None, 200, duration=0.25) # 移动到绝对Y坐标
gui.moveRel(100, 0, duration=0.25)   # 向右移
gui.moveRel(0, 100, duration=0.25)   # 向下移
gui.moveRel(-100, 0, duration=0.25)  # 向左移
gui.moveRel(0, -100, duration=0.25)  # moveRel() 等同 move()
'''
pyautogui.moveTo(100, 100, 1, pyautogui.easeInBack) 移动特效:折返一次,
easeInQuad 匀加速,easeOutQuad 匀减速,easeInOutQuad 中段加速,easeInBounce 折返两次,easeInElastic 折返闪现
'''

# 2.鼠标拖动
gui.moveTo(800, 200)                    # 定当前坐标(800,200)
gui.dragTo(600, 300, 1, button='left')  # 从当前坐标(800,200),左键拖动到绝对坐标(600,300),1秒时间
gui.dragRel(200, -100, duration=0.2)    # 从当前坐标(600,300),左键拖动到相对坐标(800,200),0.2秒
'''dragRel() 等同 drag()'''

# 3.鼠标点击
gui.mouseDown()                   # 左键按下
gui.mouseUp()                     # 左键释放
gui.mouseDown(800, 200, 'right')  # 在坐标点按下右键
gui.mouseUp(800, 500, 'right')    # 在坐标点释放右键

gui.click()                       # 当前位置左击一下
gui.doubleClick()                 # 当前位置左击二下
gui.tripleClick()                 # 当前位置左击三下

gui.click(x=1200, y=200, clicks=2, interval=0.5, button="right", duration=0)
gui.doubleClick(800, 400, 0.5, button="right")   # 坐标点连续右击两次,间隔0.5秒
'''
x=X坐标, y=Y坐标, clicks=点击次数, interval=点击间隔, button='left'|'middle'|'right', duration=鼠标移动用时)
'''

# 4.滚轮控制
gui.scroll(500)             # 向下滚动,500单位
gui.scroll(-500)            # 向上滚动,500单位
gui.scroll(500, 800, 200)   # 在(800, 800)坐标处向下滚动

gui.hscroll(-1000)          # 能水平滚动,也能上下滚动
gui.vscroll(-1000)          # 类似 hscroll,未做考究

二、按键控制

import pyautogui as gui

# 1.光标处:文本输入, 按键输入
gui.write('Hello world!')
gui.typewrite(['a', 'b', 'c', '_', 'backspace', 'enter'], interval=0.5)
'''interval: int|float = 输入延迟 '''

# 2.按键下压与释放
gui.keyDown("shift")         # 按键下压
gui.keyUp("shift")           # 按键释放

gui.press("a")               # 下压并释放
gui.press(['a', 'a', 'a'])   # 连续下压及释放3次
gui.press('a', presses=3)
gui.press('a', presses=3, interval=0.2)
gui.press('a', 3, 0.2)

gui.hotkey('ctrl', 'shift', 'esc')
gui.hotkey('win', 'r')       # 组合键
gui.hotkey('alt', 'tab', 'shift', 'tab', interval=0.2)
'''
presses:int = 按压次数, interval: int|float = 按压间隔时间
pyautogui.KEYBOARD_KEYS 支持按键一览
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\t', '\n', '\r', '\\', '/',
 '+', '-', '=', '<', '>', '(', ')', '{', '}', '[', ']', '|', '`', '~', '_',
 ' ', ',', '.', ':', ';', "'", '"', '?', '!', '@', '#', '$', '%', '^', '&', '*',

 'ctrl', 'alt', 'shift', 'win', 'backspace', 'left', 'right', 'up', 'down', 'capslock', 'scrolllock',
 'tab', 'enter', 'esc', 'del', 'delete', 'fn', 'home', 'end', 'pagedown', 'pageup', 'pgdn', 'pgup',
 'ctrlleft', 'ctrlright', 'altleft', 'altright', 'shiftleft', 'shiftright', 'winleft', 'winright',
 'num0', 'num1', 'num2', 'num3', 'num4', 'num5', 'num6', 'num7', 'num8', 'num9', 'numlock',
 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12',
 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20', 'f21', 'f22', 'f23', 'f24',

 'accept', 'add', 'apps', 'browserback', 'browserfavorites', 'browserforward', 'browserhome',
 'browserrefresh', 'browsersearch', 'browserstop', 'clear', 'convert',  'decimal','divide', 'escape',
 'execute', 'final', 'hanguel', 'hangul', 'hanja', 'help', 'insert', 'junja', 'kana', 'kanji',
 'launchapp1', 'launchapp2', 'launchmail', 'launchmediaselect', 'modechange', 'multiply', 'nexttrack',
 'nonconvert', 'pause',  'playpause', 'prevtrack', 'print', 'printscreen', 'prntscrn', 'prtsc', 'prtscr',
 'return', 'select', 'separator', 'sleep', 'space', 'stop', 'subtract', 'volumedown', 'volumemute',
 'volumeup', 'yen', 'command', 'option', 'optionleft', 'optionright' ]
'''

三、屏幕操作

  • 3.1 屏幕截取
import datetime
import pyautogui as gui

t = datetime.datetime.now().strftime('%Y%m.%d%H.%M%S%f')[3:-5]
''' 暂定截图命名格式为:Screenshot_4X2.1X2X.4X4X9.png '''

# 1.区域截屏,全屏截图,均会覆盖同名文件
print(gui.screenshot(rf'.\Screenshot_{t}.png', region=(100, 100, 400, 300)))   # 截屏范围
print(gui.screenshot(rf'.\Screenshot_{t}.png'))   
'''
>>> 
>>> 
region = (X轴截图起点, Y轴截图起点, 起点水平向右截取范围≈截图宽度, 起点垂直向下截取范围≈截图高度)
'''

# 2 获取坐标点的 RGB 值,判断坐标点的 RGB 值,误差 ±10
print("RGB:", gui.screenshot().getpixel((400, 300)))
print("RGB:", gui.pixel(400, 300))
gui.pixelMatchesColor(400, 300, (255, 255, 252), tolerance=10) 
'''
>>> RGB: (55, 25, 255)
>>> RGB: (55, 25, 255)
>>> False              
'''
  • 3.2、屏幕图像识别
import pyautogui as gui

# 先截取一张小图用于匹配,匹配不到会报错:ImageNotFoundException 
gui.screenshot(rf'.\Screenshot.png', region=(400, 300, 64, 64))

# 1.获取对象的坐标范围,它只需要匹配一张屏幕上相似的图像。对象:指被识别图像,即:r'.\Screenshot.png'
location = gui.locateOnScreen(r'.\Screenshot.png', confidence=0.9)
print(location)
'''Box(left=400, top=300, width=64, height=64), confidence=相似度90%'''

# 2.获取对象的边缘值:左
print(location.left)
'''400'''

# 3.获取对象的中心坐标
print(gui.center(location))
'''Point(x=432, y=332)'''

# 4.获取对象的坐标范围,可识别屏幕上所有(多个)相似的图像,用 list 记录, 准确率高于 locateOnScreen()
print(list(gui.locateAllOnScreen(r'.\Screenshot.png')))
ALL = []
for i in gui.locateAllOnScreen(r'.\Screenshot.png'):
    ALL.append(i)
print(ALL)
'''[Box(left=400, top=300, width=64, height=64), Box(left=621, top=254, width=64, height=64)]'''
'''[Box(left=np.int64(400), top=np.int64(300), width=64, height=64)...新版 Box 采用 numpy 64位整数'''

四、消息窗口

import pyautogui as gui

# 1.输入框
print(gui.prompt(text="请输入",title="提示",default="A"))
'''
>>> 输入值 A 或 None
text: str = "输入提示", title: str = "标题栏", default: str = "待输入默认值", root: Any | None = None, timeout: Any | None = None
'''

# 2. 密码框
print(gui.password('Enter password (text will be hidden)'))
print(gui.password('Enter password (text will be hidden)', '提示', "", '★', "", 9000))  # 9秒超时
'''
>>> 输入值 或 None
text: str = "", title: str = "", default: str = "", mask: str = "*", root: Any | None = None, timeout: Any | None = None
'''

# 3.选择框
print(gui.confirm(text='请问是否需要继续?',title="提示"))
print(gui.confirm(text='请问是否需要继续?',title="提示", buttons=['A', 'B', 'C']))
print(gui.confirm(text='', title='', buttons=range(1, 11)))
'''
>>> OK 或 Cancel
>>> A 或 B 或 C
text: str = "提示内容",title: str = "标题栏", buttons: Any = (pymsgbox.OK_TEXT, pymsgbox.CANCEL_TEXT),root: Any | None = None, timeout: Any | None = None, icon: int = QUESTION, _tkinter: bool = False
'''

# 4.提示框
print(gui.alert(text="提示",title="提示"))
'''
>>> OK
text: str = "文本内容", title: str = "标题栏", button: str = pymsgbox.OK_TEXT, root: Any | None = None, timeout: Any | None = None, icon: int = NO_ICON, _tkinter: bool = False
'''

五、练习用例:

# 1.获取鼠标在屏幕中的位置,并获取像素点 RGB 值
import pyautogui as gui, time

def get_cursor_rgb():
    X, Y = 0, 0
    while True:
        time.sleep(0.1)
        x, y = gui.position()
        if x != X or y != Y:
            X, Y = x, y
            rgb = gui.pixel(x, y)
            print(f'\r{x},{y}, RGB:{rgb}', end="")

if __name__ == "__main__":
    get_cursor_rgb()
# 2.根据截图,光标自动移到相似的图像区
import pyautogui as gui

gui.moveTo(100, 100, 1, gui.easeInOutQuad)                         # 先移动鼠标
gui.screenshot(rf'.\Screenshot.png', region=(400, 300, 200, 200))  # 先截取一张200×200的图像

try:
    location = list(gui.locateAllOnScreen(r'.\Screenshot.png', confidence=0.9))
    for i in range(len(location)):
        x, y = gui.center(location[i])
        gui.moveTo(x, y, 0.5, gui.easeOutQuad)

except Exception as e:
    print("图像未能识别")

未能详尽处,请多评论指导,谢谢!侵删。

你可能感兴趣的:(Python,python)