目录:
PyAutoGUI 用于通过代码控制鼠标、键盘和屏幕,实现图形用户界面(GUI)的自动化操作。广泛应用于软件测试、重复性任务处理、游戏脚本开发等领域。
安装依赖:
$ pip install pyautogui -i https://pypi.tuna.tsinghua.edu.cn/simple
为了获得完整的图像识别功能,建议同时安装 OpenCV 和 Pillow:
$ pip install opencv-python pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
import pyautogui
# 获取屏幕信息
screen_width, screen_height = pyautogui.size()
print(f"屏幕尺寸:{screen_width}x{screen_height}")
# 输出: 屏幕尺寸:1920x1080
import pyautogui
import time
# 获取屏幕信息
screen_width, screen_height = pyautogui.size()
print(f"屏幕尺寸:{screen_width}x{screen_height}")
# 移动鼠标到屏幕中央并双击
pyautogui.moveTo(screen_width/2, screen_height/2, duration=1)
pyautogui.doubleClick()
time.sleep(1)
import pyautogui
# 在记事本等输入框位置输入Hello World
pyautogui.write('Hello World!', interval=0.1)
pyautogui.press('enter')
MacOS 或 Window 底部会有一些 App 的小图标,点击可以切换应用。截图谷歌浏览器小图标保存为 Chrome.jpg 图片,如下代码 pyautogui 会自动找到图片对应的坐标,然后进行点击,无需硬编码坐标。
import pyautogui
import time
chrome_icon = pyautogui.locateCenterOnScreen('chrome.jpg', confidence=0.9)
pyautogui.click(chrome_icon)
time.sleep(3)
↶ 返回首页 ↶