7Automate the Boring Stuff with Python(第2版)

GUI自动化

桌面自动化

pyautogui键盘鼠标控制截图图像识别

🎯 AI 时代的学习建议:不要只读理论。理解这一章的设计动机(为什么需要这个概念?)和边界条件(什么情况下会失效?)。当 AI 生成的代码涉及这些概念时,你能判断它是否用对了场景。AI 能帮你总结内容,但无法替代你亲手阅读、思考、建立直觉的过程。

第7章:GUI自动化

一、导读

1.1 本章学习目标

第7章讲解 Python 的 GUI 自动化:pyautogui 控制键盘鼠标、截图、图像识别。

本章核心学习目标:

  • 掌握 pyautogui:控制键盘和鼠标
  • 理解截图和图像定位
  • 实现桌面自动化脚本

1.2 为什么本章如此重要

GUI 自动化能操作任何桌面应用,即使没有 API 或命令行接口。

1.3 核心问题引导

pyautogui 如何模拟键盘和鼠标?

如何定位屏幕上的图像?

GUI 自动化有什么风险和限制?


二、核心概念详解

2.1 pyautogui 基础

python
import pyautogui
import time

# 屏幕尺寸
width, height = pyautogui.size()
print(f"Screen: {width}x{height}")

# 鼠标位置
x, y = pyautogui.position()
print(f"Mouse: ({x}, {y})")

# 移动鼠标
pyautogui.moveTo(100, 100, duration=0.5)
pyautogui.moveRel(50, 0, duration=0.5)  # 相对移动

# 点击
pyautogui.click(100, 100)
pyautogui.doubleClick(100, 100)
pyautogui.rightClick(100, 100)

# 键盘输入
pyautogui.typewrite('Hello World', interval=0.05)
pyautogui.press('enter')
pyautogui.hotkey('ctrl', 'c')  # 组合键

# 截图
screenshot = pyautogui.screenshot()
screenshot.save('screen.png')

# 定位图像
location = pyautogui.locateOnScreen('button.png', confidence=0.9)
if location:
    pyautogui.click(location)

2.2 安全机制

python
# 安全设置
pyautogui.PAUSE = 1  # 每次操作后暂停 1 秒
pyautogui.FAILSAFE = True  # 鼠标移到左上角时中止

# 安全使用
def safe_automation():
    print("Starting in 5 seconds...")
    print("Move mouse to top-left corner to abort")
    time.sleep(5)
    
    # 自动化操作
    pyautogui.click(500, 500)
    pyautogui.typewrite('automated text')
    pyautogui.press('enter')

三、实战案例

3.1 案例一:自动填写表单

python
import pyautogui
import time

def fill_form():
    """自动填写在线表单"""
    print("Switch to browser window in 3 seconds...")
    time.sleep(3)
    
    # 点击第一个输入框
    pyautogui.click(x=400, y=300)
    time.sleep(0.5)
    
    # 填写姓名
    pyautogui.typewrite('Alice Smith', interval=0.05)
    pyautogui.press('tab')
    
    # 填写邮箱
    pyautogui.typewrite('alice@example.com', interval=0.05)
    pyautogui.press('tab')
    
    # 填写电话
    pyautogui.typewrite('555-1234', interval=0.05)
    
    # 点击提交
    pyautogui.click(x=400, y=600)
    
    print("Form submitted!")

# fill_form()

四、本章小结

pyautogui 控制键盘鼠标实现 GUI 自动化

截图和图像定位可以识别屏幕元素

使用 FAILSAFE 防止失控


五、思考与练习

GUI 自动化比 API 调用有什么劣势?

如何处理动态变化的界面?


7/7GUI自
0%