每日一包 - PyAutoGUI

373 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第20天,点击查看活动详情

介绍

PyAutoGUI是一个跨平台GUI自动化Python模块。可以使用代码控制鼠标和键盘。本文主要介绍该模块的入门级使用,建议更多更全面的使用方式可以参考官方文档pyautogui.readthedocs.org进行学习。

Python2和Python3都支持该模块的使用。

安装和使用

安装

pip install pyautogui

使用 - 控制键盘和鼠标

PyAutoGUI使用的x, y坐标在屏幕的左上角有0,0原点坐标。x坐标向右增加,但y坐标向下增加。在尺寸为1920 x 1080像素的屏幕上,坐标0,0表示左上角,而坐标1919,1079表示右下角。目前,PyAutoGUI只在主监视器上工作。PyAutoGUI对于第二个显示器的屏幕不可靠(鼠标功能可能在多显示器设置上工作,也可能不能,这取决于您的操作系统和版本)。

所有由PyAutoGUI完成的键盘按下都被发送到当前有焦点的窗口,就像按下了物理键盘键一样。

import pyautogui
​
# 返回两个数字,分别是屏幕的宽度和高度(分辨率)
screenWidth, screenHeight = pyautogui.size()  # 1920 1080# 返回两个数字,即当前鼠标所在的位置
currentMouseX, currentMouseY = pyautogui.position()
​
# 将鼠标移动至指定坐标(100, 150)
pyautogui.moveTo(100, 150)
​
# 鼠标在当前位置进行点击操作
pyautogui.click()
​
# 鼠标在指定坐标位置进行点击操作
pyautogui.click(200, 220)
​
# 鼠标向下移动10像素位置
pyautogui.move(None, 10)
​
# 鼠标在当前位置进行双击操作
pyautogui.doubleClick()
​
# 在游标位置写hello world,每个字母之间间隔0.25s
pyautogui.write('Hello world!', interval=0.25)
​
# 模拟按esc键
pyautogui.press('esc')
pyautogui.keyDown('shift')
pyautogui.write(['left', 'left', 'left', 'left', 'left', 'left'])
pyautogui.keyUp('shift')
pyautogui.hotkey('ctrl', 'c')

使用 - 弹出框

该模块也支持弹出框操作,分为普通弹出框、确认信息弹出框、选择框、输入框、密码框等。

    >>> import pyautogui
    >>> pyautogui.alert('This is an alert box.')  # 普通弹出框
    'OK'
    >>> pyautogui.confirm('Shall I proceed?')  # 确认信息弹出框
    'Cancel'
    >>> pyautogui.confirm('Enter option.', buttons=['A', 'B', 'C'])  # 选择弹出框
    'B'
    >>> pyautogui.prompt('What is your name?')  # 输入弹出框
    'Al'
    >>> pyautogui.password('Enter password (text will be hidden)')  # 密码输入弹出框
    'swordfish'

使用 - 截图功能

PyAutoGUI模块借助pillow实现图片相关的功能,比如下述代码实现截取全屏:

import pyautogui
​
img1 = pyautogui.screenshot()
img1.save("img1.png")

也可以定位图像在屏幕上的位置,然后根据位置进行一些其他的操作:

import pyautogui
button7location = pyautogui.locateOnScreen('button.png') # returns (left, top, width, height) of matching region
button7location # (1416, 562, 50, 41)
buttonx, buttony = pyautogui.center(button7location)
buttonx, buttony  # (1441, 582)
pyautogui.click(buttonx, buttony)  # clicks the center of where the button was found

locateCenterOnScreen()方法可以返回匹配区域的中心位置:

import pyautogui
buttonx, buttony = pyautogui.locateCenterOnScreen('button.png') # returns (x, y) of matching region
buttonx, buttony  # (1441, 582)
pyautogui.click(buttonx, buttony)  # clicks the center of where the button was found

总结

该模块提供了很多使用代码操作GUI的方法,总结一下该模块的特点:

  • 移动鼠标并单击其他应用程序的窗口。
  • 向应用程序发送击键(例如,填写表格)。
  • 截取屏幕截图,并给出一个图像(例如,一个按钮或复选框),然后在屏幕上找到它。
  • 找到应用程序的窗口,然后移动、调整大小、最大化、最小化或关闭它(目前仅限 Windows)。
  • 显示警报和消息框。

关于该模块更多的知识请参考官方文档。