No24: PyAutoGUI 实现桌面自动化
摘要
PyAutoGUI 是一个跨平台的桌面自动化工具,能够模拟鼠标点击、键盘输入、屏幕截图与图像识别,适用于重复性桌面任务(如表单填写、游戏操作、批量文件处理)。本集通过代码+截图+输出日志的实战形式,带你掌握从基础操作到复杂任务的全流程自动化。

核心概念与代码实战
1. 基础操作:鼠标与键盘控制
安装命令:
bash
pip install pyautogui
鼠标控制:
python
import pyautogui
import time
# 移动鼠标到坐标 (500, 300)
pyautogui.moveTo(500, 300, duration=1)
# 模拟点击(左键单击)
pyautogui.click()
# 滚轮滚动(向上滚动 200 单位)
pyautogui.scroll(200)
键盘输入:
python
# 输入文本
pyautogui.write("Hello, PyAutoGUI!", interval=0.1)
# 组合键操作(Ctrl+C)
pyautogui.hotkey("ctrl", "c")
效果验证:
python
print(f"当前鼠标位置:{pyautogui.position()}") # 输出实时坐标
2. 截屏与图像识别
场景:通过屏幕上的图标定位并点击按钮。
python
# 截取屏幕并保存
screenshot = pyautogui.screenshot()
screenshot.save("screenshot.png")
# 查找图标位置(需提前保存图标图片)
button_location = pyautogui.locateOnScreen("submit_button.png")
if button_location:
# 计算图标中心点并点击
button_center = pyautogui.center(button_location)
pyautogui.click(button_center)
else:
print("图标未找到!")
输出示例:
图标位置:Box(left=200, top=150, width=50, height=30)
3. 脚本调试与异常处理
问题场景 :图像识别失败导致脚本崩溃。
解决方案:
python
try:
# 设置超时时间为 5 秒
button_location = pyautogui.locateOnScreen(
"save_icon.png",
confidence=0.8, # 允许 80% 相似度
grayscale=True # 灰度匹配提升速度
)
if not button_location:
raise Exception("图标匹配失败!")
except Exception as e:
print(f"错误:{e}")
# 回退到手动输入坐标
pyautogui.click(100, 200)
调试技巧:
- 使用
pyautogui.PAUSE = 1
控制操作间隔 - 启用
pyautogui.FAILSAFE = True
(鼠标移至左上角强制停止脚本)
实战案例
案例 1:自动化填写表单
场景:批量填写 Excel 表格中的数据到某个桌面应用。
python
import pyautogui
import pandas as pd
# 读取 Excel 数据
data = pd.read_excel("data.xlsx")
for index, row in data.iterrows():
# 定位输入框并填写
pyautogui.click(300, 400) # 姓名输入框
pyautogui.write(row["姓名"])
pyautogui.press("tab") # 跳转到年龄输入框
pyautogui.write(str(row["年龄"]))
# 提交表单
pyautogui.press("enter")
time.sleep(1) # 等待页面刷新
输出示例:
已提交姓名:张三,年龄:25
已提交姓名:李四,年龄:30
案例 2:模拟游戏中的简单操作
场景:自动玩"键盘反应速度"游戏。
python
# 监听屏幕特定区域的变化
game_region = (400, 200, 200, 100)
while True:
# 截取游戏区域
region_screenshot = pyautogui.screenshot(region=game_region)
# 检测红色方块出现
if pyautogui.pixelMatchesColor(500, 250, (255, 0, 0)):
pyautogui.press("space") # 按空格键得分
案例 3:批量重命名文件
场景:将文件夹中的 100 张图片按规则重命名。
python
import os
import pyautogui
# 打开文件资源管理器
os.system("explorer.exe .\\images")
time.sleep(2)
# 依次重命名文件
for i in range(1, 101):
pyautogui.hotkey("ctrl", "a") # 全选文件
pyautogui.press("f2") # 重命名
pyautogui.write(f"photo_{i:03d}") # 格式化名称(photo_001)
pyautogui.press("enter")
time.sleep(0.5)
扩展思考
1. PyAutoGUI 与其他工具的结合
-
与 Selenium 结合 :
python# 用 Selenium 处理网页,PyAutoGUI 处理下载弹窗 driver.get("https://example.com/download") pyautogui.press("enter") # 自动确认下载对话框
-
打包为可执行文件 :
bashpip install pyinstaller pyinstaller --onefile your_script.py
2. 安全性和法律合规性
- 风险提示 :
- 避免自动化操作金融交易、社交账号等敏感场景
- 部分软件(如游戏)可能禁止自动化脚本
- 合规建议 :
- 仅用于个人效率提升或授权场景
- 遵守《计算机软件保护条例》和平台规则
总结
通过本实战,你已掌握:
- PyAutoGUI 的核心操作(鼠标、键盘、图像识别)
- 复杂任务的异常处理与调试技巧
- 从表单填写到游戏模拟的完整案例
- 自动化脚本的法律边界与安全实践
下集预告 :
《No25: Python 并发编程:从多线程到异步 IO》将带你突破单线程性能瓶颈,实现高并发任务处理!
附:运行环境
- 环境要求:Python 3.7+、Windows/macOS/Linux