PyAutoGUI 自动化教程
PyAutoGUI 是一个 Python 库,可以控制鼠标、键盘,实现自动化操作。下面是详细教程:
目录
安装与导入
# 安装 PyAutoGUI
pip install pyautogui
# 导入库
import pyautogui
基础配置
import pyautogui
import time
# 安全设置 - 非常重要!
pyautogui.FAILSAFE = True # 启用故障安全(鼠标移动到屏幕左上角会触发异常)
pyautogui.PAUSE = 1.0 # 每个函数后暂停1秒
# 获取屏幕尺寸
screen_width, screen_height = pyautogui.size()
print(f"屏幕尺寸: {screen_width} x {screen_height}")
鼠标控制
移动鼠标
# 移动到绝对坐标
pyautogui.moveTo(100, 200, duration=1.5) # 用1.5秒移动到(100,200)
# 移动到相对位置
pyautogui.move(50, 0, duration=0.5) # 向右移动50像素
# 获取当前位置
current_x, current_y = pyautogui.position()
print(f"当前鼠标位置: ({current_x}, {current_y})")
点击操作
# 基本点击
pyautogui.click() # 当前位置单击
pyautogui.click(x=100, y=200) # 指定位置单击
pyautogui.click(button='right') # 右键单击
pyautogui.doubleClick() # 双击
pyautogui.tripleClick() # 三击
# 按下和释放
pyautogui.mouseDown() # 按下鼠标
time.sleep(0.5)
pyautogui.mouseUp() # 释放鼠标
# 拖拽操作
pyautogui.dragTo(300, 400, duration=2) # 拖拽到绝对位置
pyautogui.drag(0, 100, duration=1) # 相对拖拽
滚动
pyautogui.scroll(10) # 向上滚动10个单位
pyautogui.scroll(-10) # 向下滚动10个单位
pyautogui.hscroll(50) # 水平滚动
键盘控制
输入文本
# 输入字符串
pyautogui.write('Hello World!', interval=0.1) # 每个字符间隔0.1秒
# 按单个键
pyautogui.press('enter') # 按回车
pyautogui.press('tab') # 按Tab
pyautogui.press('esc') # 按ESC
# 组合键
pyautogui.hotkey('ctrl', 'c') # Ctrl+C
pyautogui.hotkey('ctrl', 'v') # Ctrl+V
pyautogui.hotkey('alt', 'f4') # Alt+F4
# 按下和释放
pyautogui.keyDown('shift') # 按下Shift
pyautogui.press('a') # 按A
pyautogui.keyUp('shift') # 释放Shift
特殊按键
# 常用特殊键
keys = ['enter', 'tab', 'esc', 'backspace', 'delete',
'up', 'down', 'left', 'right',
'f1', 'f2', 'f3', 'f4', 'f5',
'ctrl', 'alt', 'shift', 'win']
for key in keys:
pyautogui.press(key)
time.sleep(0.5)
屏幕操作
截屏与图像识别
# 截取全屏
screenshot = pyautogui.screenshot()
screenshot.save('screenshot.png')
# 截取区域
region_screenshot = pyautogui.screenshot(region=(0, 0, 300, 400))
# 获取像素颜色
pixel_color = pyautogui.pixel(100, 200)
print(f"像素颜色: {pixel_color}")
# 图像识别(需要先准备图片)
try:
# 在屏幕上查找图片位置
location = pyautogui.locateOnScreen('button.png', confidence=0.9)
if location:
center = pyautogui.center(location)
pyautogui.click(center)
except:
print("未找到图片")
多图片匹配
# 查找所有匹配项
all_locations = list(pyautogui.locateAllOnScreen('icon.png'))
# 检查是否存在
if pyautogui.locateOnScreen('icon.png') is not None:
print("找到了图标!")
消息框功能
# 显示消息框
pyautogui.alert('这是一个警告!', '警告')
pyautogui.confirm('要继续吗?', '确认')
pyautogui.prompt('请输入你的名字:', '输入')
password = pyautogui.password('请输入密码:', '密码输入', mask='*')
综合示例
示例1:自动化登录
import pyautogui
import time
def auto_login(username, password):
"""自动化登录示例"""
print("5秒后开始,请切换到目标窗口...")
time.sleep(5)
# 点击用户名输入框
pyautogui.click(500, 300)
time.sleep(0.5)
# 输入用户名
pyautogui.write(username, interval=0.1)
time.sleep(0.5)
# 按Tab切换到密码框
pyautogui.press('tab')
time.sleep(0.5)
# 输入密码
pyautogui.write(password, interval=0.1)
time.sleep(0.5)
# 点击登录按钮
pyautogui.click(500, 400)
print("登录完成!")
# 使用示例
# auto_login('your_username', 'your_password')
示例2:批量重命名文件
import pyautogui
import time
def batch_rename():
"""批量重命名文件"""
print("5秒后开始...")
time.sleep(5)
# 选择第一个文件
pyautogui.click(100, 100)
time.sleep(0.5)
# F2重命名
pyautogui.press('f2')
time.sleep(0.5)
# 输入新名称
pyautogui.write('file_001', interval=0.05)
time.sleep(0.5)
# 按Enter确认
pyautogui.press('enter')
time.sleep(0.5)
# 用Tab选择下一个文件
for i in range(2, 11):
pyautogui.press('tab')
time.sleep(0.2)
pyautogui.press('f2')
time.sleep(0.2)
pyautogui.write(f'file_{i:03d}', interval=0.05)
time.sleep(0.2)
pyautogui.press('enter')
time.sleep(0.2)
示例3:屏幕监控
import pyautogui
import time
from datetime import datetime
def screen_monitor(check_interval=5, duration=60):
"""屏幕监控 - 检测特定颜色或图片"""
print(f"开始监控,持续{duration}秒...")
start_time = time.time()
while time.time() - start_time < duration:
# 检查特定位置的颜色
color = pyautogui.pixel(500, 500)
print(f"{datetime.now().strftime('%H:%M:%S')} - 颜色: {color}")
# 如果有红色出现
if color[0] > 200 and color[1] < 50 and color[2] < 50:
pyautogui.alert('检测到红色!', '警告')
break
time.sleep(check_interval)
注意事项
1. 安全建议
# 1. 始终启用故障安全
pyautogui.FAILSAFE = True
# 2. 设置暂停时间
pyautogui.PAUSE = 0.5 # 每个操作后暂停0.5秒
# 3. 测试脚本
def test_mouse():
print("移动鼠标到左上角停止")
for i in range(10):
pyautogui.move(100, 0)
time.sleep(0.5)
2. 调试技巧
import pyautogui
import time
# 实时显示鼠标位置
print("按Ctrl+C停止")
try:
while True:
x, y = pyautogui.position()
position_str = f"X: {x:4d}, Y: {y:4d}"
color = pyautogui.pixel(x, y)
color_str = f"RGB: ({color[0]:3d}, {color[1]:3d}, {color[2]:3d})"
print(position_str + " " + color_str, end='')
print('\b' * len(position_str + " " + color_str), end='', flush=True)
time.sleep(0.1)
except KeyboardInterrupt:
print("\n停止")
3. 常见问题解决
- 多显示器支持:
# PyAutoGUI 默认支持多显示器
# 坐标可以是负值或超过主屏幕尺寸
- 分辨率适应:
# 使用相对坐标
screen_width, screen_height = pyautogui.size()
center_x, center_y = screen_width // 2, screen_height // 2
- 性能优化:
# 降低图像识别精度以提高速度
location = pyautogui.locateOnScreen('image.png', confidence=0.7, grayscale=True)
4. 平台差异
- macOS: 可能需要权限设置(系统偏好设置 → 安全性与隐私 → 辅助功能)
- Linux: 可能需要安装依赖:
sudo apt-get install scrot python3-tk python3-dev - Windows: 通常无需额外配置
进阶功能
1. 创建GUI自动化脚本
import pyautogui
import time
class AutoGUI:
def __init__(self):
self.screen_width, self.screen_height = pyautogui.size()
def center_click(self):
"""点击屏幕中心"""
center_x = self.screen_width // 2
center_y = self.screen_height // 2
pyautogui.click(center_x, center_y)
def type_with_enter(self, text):
"""输入文本并回车"""
pyautogui.write(text, interval=0.1)
pyautogui.press('enter')
def safe_execute(self, func, *args, **kwargs):
"""安全执行函数"""
try:
func(*args, **kwargs)
except pyautogui.FailSafeException:
print("用户中断操作(鼠标移动到左上角)")
return False
return True
# 使用示例
auto = AutoGUI()
auto.safe_execute(auto.center_click)
2. 错误处理
import pyautogui
import traceback
def safe_click(x, y, retries=3):
"""安全的点击操作,带有重试机制"""
for attempt in range(retries):
try:
pyautogui.click(x, y)
return True
except Exception as e:
print(f"点击失败,重试 {attempt + 1}/{retries}: {e}")
time.sleep(1)
return False
# 使用图像识别点击
def click_image(image_path, max_attempts=5):
"""查找并点击图片"""
for _ in range(max_attempts):
try:
location = pyautogui.locateOnScreen(image_path, confidence=0.8)
if location:
center = pyautogui.center(location)
pyautogui.click(center)
return True
except:
time.sleep(1)
print(f"未找到图片: {image_path}")
return False
总结
PyAutoGUI 是一个功能强大的自动化工具,适用于:
- 自动化重复性GUI任务
- 创建演示或教程
- 软件测试
- 游戏自动化
- 屏幕监控
通过合理使用 PyAutoGUI,可以大大提高工作效率,自动化繁琐的GUI操作。