Python 操作系统桌面自动化编程(PyAutoGUI)从入门到实战
这是一份专为移动端阅读优化的 PyAutoGUI Python 教程,语言通俗、步骤清晰、示例完整。全程用同步模式演示(新手友好),所有示例都在 Windows 10/11 系统下测试通过,Mac/Linux 用户只需微调少量代码即可使用。
一、准备工作:安装与环境配置
1. 安装核心包
打开命令行,执行以下命令:
bash
pip install pyautogui # 安装PyAutoGUI核心库
pip install pyperclip # 用于中文输入(必装)
pip install opencv-python # 用于图像识别(可选)
提示:Windows 系统可能需要额外安装pillow库处理截图,执行pip install pillow即可。
2. 验证安装
创建test_install.py文件,运行以下代码:
python
import pyautogui
import pyperclip
# 打印屏幕分辨率
screen_width, screen_height = pyautogui.size()
print(f"屏幕分辨率: {screen_width}x{screen_height}")
# 获取当前鼠标位置
x, y = pyautogui.position()
print(f"当前鼠标位置: ({x}, {y})")
# 弹出测试消息框
pyautogui.alert(text="PyAutoGUI安装成功!", title="验证结果", button="OK")
运行后能看到系统消息框弹出,说明安装成功。
二、核心概念:PyAutoGUI 的核心设计
PyAutoGUI 是一个跨平台的桌面自动化库,核心设计理念是模拟人类操作,主要包括:
- 坐标系统:屏幕左上角为原点 (0,0),向右为 x 轴正方向,向下为 y 轴正方向
- 绝对定位:基于屏幕坐标的精确操作(如
moveTo(100, 200)) - 相对定位:基于当前鼠标位置的相对操作(如
moveRel(50, 0)向右移动 50 像素) - 故障安全机制:默认启用,当鼠标移到屏幕四角时会抛出异常终止脚本,防止失控
标准写法模板(记住这个格式):
python
import pyautogui
import time
# 基础配置(可选)
pyautogui.FAILSAFE = True # 启用故障安全(推荐)
pyautogui.PAUSE = 0.5 # 每个操作后暂停0.5秒(防止操作过快)
def basic_automation():
# 1. 等待3秒,方便切换到目标窗口
time.sleep(3)
# 2. 执行自动化操作(核心代码写这里)
pyautogui.moveTo(500, 500, duration=1) # 1秒内移动到(500,500)
pyautogui.click() # 点击鼠标左键
# 3. 结束提示
pyautogui.alert("操作完成!")
basic_automation()
三、鼠标控制:精准操控指针
1. 鼠标移动
python
import pyautogui
import time
def mouse_movement():
time.sleep(3) # 准备时间
# 1. 绝对移动(直接到指定坐标)
pyautogui.moveTo(100, 100, duration=0.5) # 0.5秒平滑移动
time.sleep(0.5)
# 2. 相对移动(从当前位置偏移)
pyautogui.moveRel(200, 0, duration=0.5) # 向右移动200像素
time.sleep(0.5)
pyautogui.moveRel(0, 200, duration=0.5) # 向下移动200像素
# 3. 快速移动(无动画)
pyautogui.moveTo(800, 400)
print("鼠标移动完成!")
mouse_movement()
2. 鼠标点击
python
import pyautogui
import time
def mouse_clicks():
time.sleep(3)
# 1. 左键单击(默认)
pyautogui.click()
time.sleep(0.5)
# 2. 双击/右键/中键
pyautogui.doubleClick() # 双击
time.sleep(0.5)
pyautogui.rightClick() # 右键
time.sleep(0.5)
pyautogui.middleClick() # 中键
# 3. 自定义点击(指定坐标和按键)
pyautogui.click(x=500, y=500, button='left', clicks=3, interval=0.2)
# 解释:在(500,500)处左键点击3次,每次间隔0.2秒
mouse_clicks()
3. 拖拽与滚轮
python
import pyautogui
import time
def mouse_drag_scroll():
time.sleep(3)
# 1. 拖拽操作(按住左键移动)
pyautogui.moveTo(100, 100)
pyautogui.dragTo(300, 300, duration=1, button='left') # 绝对拖拽
# 2. 相对拖拽
pyautogui.dragRel(100, 0, duration=0.5, button='left') # 向右拖拽100像素
# 3. 滚轮操作(正数向上,负数向下)
pyautogui.scroll(10) # 向上滚动10格
time.sleep(0.5)
pyautogui.scroll(-10) # 向下滚动10格
mouse_drag_scroll()
四、键盘控制:模拟输入操作
1. 基础输入
python
import pyautogui
import time
def keyboard_basics():
time.sleep(3) # 准备时间,切换到记事本等输入窗口
# 1. 输入英文文本(间隔0.1秒,模拟真实打字)
pyautogui.write("Hello PyAutoGUI!", interval=0.1)
time.sleep(0.5)
# 2. 特殊按键
pyautogui.press("enter") # 按Enter键
pyautogui.press(["tab", "shift", "backspace"]) # 按多个键
# 3. 组合键(热键)
pyautogui.hotkey("ctrl", "a") # 全选
time.sleep(0.5)
pyautogui.hotkey("ctrl", "c") # 复制
time.sleep(0.5)
pyautogui.hotkey("ctrl", "v") # 粘贴
keyboard_basics()
2. 中文输入解决方案(重点)
PyAutoGUI 不直接支持中文输入,用剪贴板粘贴法解决:
python
import pyautogui
import pyperclip
import time
def chinese_input(text):
"""中文输入函数:先复制到剪贴板,再粘贴"""
pyperclip.copy(text) # 复制中文到剪贴板
pyautogui.hotkey("ctrl", "v") # 粘贴
def test_chinese():
time.sleep(3) # 切换到输入窗口
chinese_input("这是PyAutoGUI中文输入示例!")
pyautogui.press("enter")
chinese_input("支持任何语言和特殊字符:@#¥%……&*()")
test_chinese()
3. 高级键盘操作
python
import pyautogui
import time
def advanced_keyboard():
time.sleep(3)
# 1. 按住并释放按键
pyautogui.keyDown("shift") # 按住Shift
pyautogui.write("hello world") # 输入大写字母
pyautogui.keyUp("shift") # 释放Shift
# 2. 连续按键
pyautogui.press("arrowright", presses=5, interval=0.2) # 按右箭头5次
pyautogui.press("delete") # 删除选中内容
advanced_keyboard()
五、屏幕操作:截图与像素分析
1. 截图功能
python
import pyautogui
import time
def screenshot_demo():
time.sleep(3)
# 1. 全屏截图
screenshot = pyautogui.screenshot()
screenshot.save("full_screen.png")
# 2. 区域截图(x, y, width, height)
region_screenshot = pyautogui.screenshot(region=(100, 100, 500, 300))
region_screenshot.save("region_screen.png")
# 3. 获取像素颜色
color = pyautogui.pixel(500, 500)
print(f"坐标(500,500)的像素颜色: {color}")
# 4. 验证像素颜色
if pyautogui.pixelMatchesColor(500, 500, (255, 255, 255)):
print("该点是白色")
else:
print("该点不是白色")
screenshot_demo()
2. 图像识别定位(游戏 / 软件自动化必备)
python
import pyautogui
import time
def image_recognition():
# 确保screen_button.png文件在当前目录
# 1. 查找屏幕上的图像
button_location = pyautogui.locateOnScreen(
"screen_button.png",
confidence=0.8 # 匹配度(0-1,越高越精准)
)
if button_location:
print(f"找到目标图像: {button_location}")
# 2. 点击图像中心
x, y = pyautogui.center(button_location)
pyautogui.click(x, y)
else:
print("未找到目标图像")
# 先准备一张要识别的按钮截图,命名为screen_button.png
# image_recognition()
六、窗口管理:控制应用程序窗口
1. 窗口查找与激活
python
import pyautogui
import time
def window_management():
# 1. 查找窗口(Windows特有)
try:
# 获取所有标题包含"记事本"的窗口
notepad_windows = pyautogui.getWindowsWithTitle("记事本")
if notepad_windows:
notepad_window = notepad_windows[0]
print(f"找到记事本窗口: {notepad_window.title}")
# 2. 激活窗口
notepad_window.activate()
time.sleep(1)
# 3. 调整窗口大小和位置
notepad_window.resizeTo(600, 400)
notepad_window.moveTo(100, 100)
# 4. 最小化/最大化/关闭
# notepad_window.minimize()
# time.sleep(1)
# notepad_window.restore()
except Exception as e:
print(f"窗口操作出错: {e}")
window_management()
2. 窗口信息获取
python
import pyautogui
def get_window_info():
# 获取当前活动窗口
active_window = pyautogui.getActiveWindow()
if active_window:
print(f"当前活动窗口: {active_window.title}")
print(f"窗口位置: ({active_window.left}, {active_window.top})")
print(f"窗口大小: {active_window.width}x{active_window.height}")
get_window_info()
七、实战案例:完整的记事本自动化流程
以下是一个完整的自动化脚本,包含所有核心操作:
python
import pyautogui
import pyperclip
import time
import subprocess
def notepad_automation():
"""完整的记事本自动化流程"""
try:
# 1. 启动记事本
subprocess.Popen(["notepad.exe"])
time.sleep(2) # 等待启动
# 2. 查找并激活记事本窗口
notepad_windows = pyautogui.getWindowsWithTitle("记事本")
if not notepad_windows:
print("未找到记事本窗口")
return
notepad_window = notepad_windows[0]
notepad_window.activate()
time.sleep(1)
# 3. 输入内容(中英文混合)
pyautogui.write("PyAutoGUI记事本自动化示例\n", interval=0.05)
chinese_input("1. 自动启动记事本\n")
chinese_input("2. 自动输入中英文内容\n")
chinese_input("3. 自动保存文件\n")
# 4. 保存文件(Ctrl+S)
pyautogui.hotkey("ctrl", "s")
time.sleep(1)
# 5. 输入文件名并保存
chinese_input("自动化测试文件")
pyautogui.press("enter")
time.sleep(1)
# 6. 关闭记事本
pyautogui.hotkey("alt", "f4")
print("记事本自动化流程完成!")
except Exception as e:
print(f"自动化出错: {e}")
def chinese_input(text):
"""中文输入辅助函数"""
pyperclip.copy(text)
pyautogui.hotkey("ctrl", "v")
notepad_automation()
八、安全与最佳实践:编写可靠的自动化脚本
1. 故障安全设置
python
import pyautogui
# 启用故障安全(推荐)
pyautogui.FAILSAFE = True # 鼠标移到屏幕四角会终止脚本
pyautogui.PAUSE = 0.3 # 每个操作后暂停0.3秒,防止操作过快
# 设置操作延迟
pyautogui.MINIMUM_DURATION = 0.1 # 最小操作时间
pyautogui.MINIMUM_SLEEP = 0.05 # 操作间最小间隔
2. 坐标安全校验
python
import pyautogui
def safe_click(x, y):
"""安全点击函数:校验坐标有效性"""
screen_width, screen_height = pyautogui.size()
if 0 <= x < screen_width and 0 <= y < screen_height:
pyautogui.click(x, y)
return True
else:
print(f"坐标({x}, {y})超出屏幕范围")
return False
3. 错误处理与调试
python
import pyautogui
import time
def debug_automation():
try:
pyautogui.moveTo(10000, 10000) # 无效坐标,会触发故障安全
except pyautogui.FailSafeException:
print("触发故障安全,脚本终止")
# 调试技巧:慢动作执行
pyautogui.PAUSE = 1 # 每个操作暂停1秒
pyautogui.moveTo(500, 500, duration=2) # 2秒平滑移动
# 调试技巧:暂停等待用户确认
pyautogui.alert("请确认操作后继续...")
debug_automation()
常见问题解答
-
Q:中文输入失败?A:使用
pyperclip剪贴板粘贴法,确保输入法处于英文状态,避免输入法弹窗干扰。 -
Q:鼠标点击位置不准?A:检查屏幕缩放比例(Windows 显示设置),非 100% 缩放会导致坐标偏移;或用图像识别定位。
-
Q:脚本执行过快导致操作失败?A:设置
pyautogui.PAUSE = 0.5增加操作间隔,关键步骤前加time.sleep(1)等待响应。 -
Q:图像识别找不到目标?A:提高截图质量,调整
confidence参数(0.8 左右),确保目标在屏幕可见区域。 -
Q:Mac/Linux 系统兼容性问题?A:窗口管理功能在 Mac/Linux 上有限,改用图像识别定位;中文输入方法相同。
总结
PyAutoGUI 是 Python 桌面自动化的瑞士军刀,核心优势是简单易用、跨平台、功能全面。掌握以下要点:
- 鼠标控制:
moveTo()/click()/dragTo() - 键盘控制:
write()/press()/hotkey(),中文用剪贴板法 - 屏幕操作:
screenshot()/pixel()/ 图像识别 - 窗口管理:
getWindowsWithTitle()/ 窗口激活 / 调整 - 安全机制:启用故障安全,合理设置操作间隔
更多推荐



所有评论(0)