PyAutoGUI详解1

第1章 PyAutoGUI核心基础

1.1 安装配置与环境要求

PyAutoGUI是一个跨平台的Python GUI自动化库,支持Windows、macOS和Linux系统。它通过模拟鼠标和键盘操作来实现自动化任务。

系统要求
  • Python 3.7+
  • 操作系统:Windows 7+、macOS 10.13+、Linux(主流发行版)
  • 屏幕分辨率:建议1920x1080或更高
安装方法
bash 复制代码
# 基础安装
pip install pyautogui

# 完整安装(包含所有依赖)
pip install pyautogui[opencv]

# macOS额外依赖
pip install pyobjc-core pyobjc
依赖库说明
python 复制代码
# PyAutoGUI依赖关系图
"""
PyAutoGUI
├── PyScreeze (屏幕截图和图像识别)
├── Pillow (图像处理)
├── pymsgbox (消息框)
├── pytweening (缓动函数)
└── opencv-python (可选,用于图像识别加速)
"""

1.2 核心概念与工作原理

PyAutoGUI的核心思想是通过编程方式控制鼠标和键盘,模拟人类操作。其工作原理如下:
Python脚本
PyAutoGUI API
操作系统API
鼠标/键盘驱动
屏幕显示
用户界面
应用程序响应

核心模块架构
python 复制代码
import pyautogui

# PyAutoGUI核心模块结构
"""
pyautogui/
├── __init__.py (主模块)
├── mouse.py (鼠标操作)
├── keyboard.py (键盘操作)
├── screenshot.py (屏幕截图)
├── imageRecognition.py (图像识别)
├── pixel.py (像素操作)
└── display.py (显示器管理)
"""

1.3 FAILSAFE安全机制详解

FAILSAFE是PyAutoGUI的安全保护机制,防止自动化脚本失控。

触发条件与配置
python 复制代码
import pyautogui

# 启用FAILSAFE机制(默认启用)
pyautogui.FAILSAFE = True

# 注意:FAILSAFE_POINTS 和 FAILSAFE_DISTANCE 不是PyAutoGUI标准属性
# 以下代码展示如何自定义实现类似功能

# 自定义安全区域检查
def check_failsafe_area(x_threshold=50, y_threshold=50):
    """
    检查鼠标是否在安全区域(屏幕左上角)
    
    Args:
        x_threshold: X轴安全阈值(像素)
        y_threshold: Y轴安全阈值(像素)
    
    Returns:
        bool: 是否在安全区域内
    """
    current_pos = pyautogui.position()
    return current_pos[0] < x_threshold and current_pos[1] < y_threshold
紧急终止方法
python 复制代码
import pyautogui
import time

# 方法1:手动将鼠标移动到屏幕左上角
def emergency_stop_demo():
    print("脚本运行中...")
    print("紧急停止:将鼠标移动到屏幕左上角")
    for i in range(10):
        pyautogui.moveTo(100 + i * 50, 100 + i * 50, duration=0.5)
        time.sleep(0.5)
    print("脚本完成")

# 方法2:捕获FailSafeException异常
def safe_automation():
    try:
        for i in range(100):
            pyautogui.moveTo(100 + i * 10, 100 + i * 10, duration=0.1)
            time.sleep(0.1)
    except pyautogui.FailSafeException:
        print("检测到紧急停止信号,脚本已终止")
        return False
    return True

# 方法3:自定义安全检查
def custom_safety_check():
    safety_counter = 0
    max_operations = 50

    for i in range(max_operations):
        # 检查鼠标位置是否异常
        current_pos = pyautogui.position()
        if current_pos[0] < 50 and current_pos[1] < 50:
            print("检测到鼠标在安全区域,停止执行")
            break

        # 执行自动化操作
        pyautogui.moveTo(100 + i * 10, 100 + i * 10, duration=0.1)
        safety_counter += 1

        # 安全计数器检查
        if safety_counter > max_operations:
            print("达到最大操作次数,安全停止")
            break

    print(f"安全执行了 {safety_counter} 次操作")
FAILSAFE工作流程

操作系统 鼠标驱动 PyAutoGUI 脚本 操作系统 鼠标驱动 PyAutoGUI 脚本 alt [在安全区域内] [不在安全区域] 执行鼠标操作 发送移动指令 更新鼠标位置 返回当前坐标 检查是否在安全区域 抛出FailSafeException 捕获异常并停止 继续执行

1.4 坐标系统与屏幕定位

PyAutoGUI使用屏幕坐标系来定位鼠标位置和屏幕区域。

绝对坐标系统
python 复制代码
import pyautogui

# 获取屏幕尺寸
screen_width, screen_height = pyautogui.size()
print(f"屏幕尺寸: {screen_width} x {screen_height}")

# 绝对坐标示例
def absolute_coordinate_demo():
    # 屏幕中心点
    center_x = screen_width // 2
    center_y = screen_height // 2

    # 四个角落
    top_left = (0, 0)
    top_right = (screen_width - 1, 0)
    bottom_left = (0, screen_height - 1)
    bottom_right = (screen_width - 1, screen_height - 1)

    print(f"屏幕中心: ({center_x}, {center_y})")
    print(f"左上角: {top_left}")
    print(f"右上角: {top_right}")
    print(f"左下角: {bottom_left}")
    print(f"右下角: {bottom_right}")

    # 移动到各个位置
    positions = [
        top_left,
        top_right,
        bottom_left,
        bottom_right,
        (center_x, center_y)
    ]

    for pos in positions:
        pyautogui.moveTo(pos[0], pos[1], duration=0.5)
        pyautogui.click()
        print(f"点击位置: {pos}")
相对坐标系统
python 复制代码
import pyautogui

def relative_coordinate_demo():
    # 获取当前鼠标位置
    current_x, current_y = pyautogui.position()
    print(f"当前位置: ({current_x}, {current_y})")

    # 相对移动
    pyautogui.move(100, 0, duration=0.5)  # 向右移动100像素
    pyautogui.move(0, 100, duration=0.5)  # 向下移动100像素
    pyautogui.move(-100, 0, duration=0.5)  # 向左移动100像素
    pyautogui.move(0, -100, duration=0.5)  # 向上移动100像素

    # 回到原点
    pyautogui.moveTo(current_x, current_y, duration=0.5)
坐标系统示意图

屏幕坐标系
原点 0,0 左上角
X轴 向右增加
Y轴 向下增加
右下角 width-1,height-1
绝对坐标
moveTo x,y
click x,y
相对坐标
move xOffset,yOffset
drag xOffset,yOffset

1.5 多显示器坐标映射

在多显示器环境下,坐标系统会变得更加复杂。

python 复制代码
import pyautogui

def multi_display_demo():
    """
    多显示器演示
    
    注意:PyAutoGUI标准库不直接提供多显示器API
    以下代码展示概念性实现,实际使用需要借助第三方库如 pygetwindow 或 screeninfo
    """
    import platform
    
    print(f"当前平台: {platform.system()}")
    print("注意:多显示器支持需要额外的库")
    print("建议安装: pip install screeninfo")
    
    try:
        # 使用 screeninfo 获取显示器信息(推荐方式)
        from screeninfo import get_monitors
        
        monitors = get_monitors()
        print(f"\n检测到 {len(monitors)} 个显示器")
        
        for i, monitor in enumerate(monitors):
            print(f"\n显示器 {i + 1}:")
            print(f"  位置: ({monitor.x}, {monitor.y})")
            print(f"  尺寸: {monitor.width} x {monitor.height}")
            print(f"  主显示器: {monitor.is_primary}")
        
        # 在不同显示器间移动鼠标
        if len(monitors) > 1:
            # 在主显示器中心
            primary = monitors[0]
            primary_center = (
                primary.x + primary.width // 2,
                primary.y + primary.height // 2
            )
            pyautogui.moveTo(primary_center[0], primary_center[1], duration=1)
            
            # 在第二个显示器中心
            secondary = monitors[1]
            secondary_center = (
                secondary.x + secondary.width // 2,
                secondary.y + secondary.height // 2
            )
            pyautogui.moveTo(secondary_center[0], secondary_center[1], duration=1)
            
    except ImportError:
        print("\n未安装 screeninfo 库")
        print("运行: pip install screeninfo")
        print("\n或者使用 pygetwindow 进行窗口管理:")
        print("运行: pip install pygetwindow")
多显示器坐标偏移计算
python 复制代码
import pyautogui

def calculate_display_offset(target_display_index=1):
    """
    计算指定显示器的坐标偏移量
    
    注意:需要使用 screeninfo 库获取多显示器信息

    Args:
        target_display_index: 目标显示器索引(从0开始)

    Returns:
        tuple: (offset_x, offset_y) 偏移量
    """
    try:
        from screeninfo import get_monitors
        monitors = get_monitors()
        
        if target_display_index >= len(monitors):
            raise IndexError(f"显示器索引 {target_display_index} 超出范围")
        
        target_monitor = monitors[target_display_index]
        
        # 计算相对于主显示器的偏移
        offset_x = target_monitor.x
        offset_y = target_monitor.y
        
        return offset_x, offset_y
        
    except ImportError:
        print("错误:需要安装 screeninfo 库")
        print("运行: pip install screeninfo")
        return (0, 0)

def move_to_display(display_index, relative_x, relative_y):
    """
    移动鼠标到指定显示器的相对位置
    
    注意:需要使用 screeninfo 库获取多显示器信息

    Args:
        display_index: 显示器索引
        relative_x: 相对X坐标
        relative_y: 相对Y坐标
    """
    offset_x, offset_y = calculate_display_offset(display_index)
    
    if offset_x == 0 and offset_y == 0 and display_index > 0:
        print("无法获取显示器偏移量")
        return

    absolute_x = offset_x + relative_x
    absolute_y = offset_y + relative_y

    pyautogui.moveTo(absolute_x, absolute_y, duration=0.5)
    print(f"移动到显示器 {display_index} 的 ({relative_x}, {relative_y})")
    print(f"绝对坐标: ({absolute_x}, {absolute_y})")

1.6 屏幕尺寸获取方法

python 复制代码
import pyautogui

def screen_size_demo():
    # 获取屏幕尺寸
    width, height = pyautogui.size()
    print(f"屏幕宽度: {width}")
    print(f"屏幕高度: {height}")

    # 计算屏幕区域
    total_pixels = width * height
    print(f"总像素数: {total_pixels:,}")

    # 常用位置计算
    center_x = width // 2
    center_y = height // 2
    quarter_x = width // 4
    quarter_y = height // 4

    print(f"\n常用位置:")
    print(f"中心点: ({center_x}, {center_y})")
    print(f"四分之一点: ({quarter_x}, {quarter_y})")
    print(f"四分之三: ({width - quarter_x}, {height - quarter_y})")

    # 屏幕区域划分
    regions = {
        '左上': (0, 0, width // 2, height // 2),
        '右上': (width // 2, 0, width // 2, height // 2),
        '左下': (0, height // 2, width // 2, height // 2),
        '右下': (width // 2, height // 2, width // 2, height // 2)
    }

    print(f"\n屏幕区域划分:")
    for name, region in regions.items():
        print(f"{name}: {region}")

1.7 基础API使用示例

python 复制代码
import pyautogui
import time

def basic_api_demo():
    """基础API综合示例"""

    # 1. 获取屏幕信息
    screen_width, screen_height = pyautogui.size()
    print(f"屏幕尺寸: {screen_width} x {screen_height}")

    # 2. 获取鼠标位置
    current_pos = pyautogui.position()
    print(f"当前鼠标位置: {current_pos}")

    # 3. 鼠标移动
    print("\n鼠标移动演示:")
    pyautogui.moveTo(100, 100, duration=0.5)
    print(f"移动到 (100, 100)")

    pyautogui.move(50, 50, duration=0.3)
    print(f"相对移动 (50, 50)")

    # 4. 鼠标点击
    print("\n鼠标点击演示:")
    pyautogui.click(200, 200)
    print(f"点击位置 (200, 200)")

    pyautogui.doubleClick(250, 250)
    print(f"双击位置 (250, 250)")

    # 5. 键盘输入
    print("\n键盘输入演示:")
    pyautogui.click(300, 300)  # 点击输入框位置
    pyautogui.write('Hello PyAutoGUI!', interval=0.1)
    print("输入文本: Hello PyAutoGUI!")

    # 6. 特殊键操作
    print("\n特殊键操作演示:")
    pyautogui.press('enter')
    print("按下回车键")

    pyautogui.hotkey('ctrl', 'a')  # 全选
    print("按下 Ctrl+A")

    # 7. 屏幕截图
    print("\n屏幕截图演示:")
    screenshot = pyautogui.screenshot()
    print(f"截图尺寸: {screenshot.size}")

    # 8. 鼠标滚轮
    print("\n鼠标滚轮演示:")
    pyautogui.scroll(3)  # 向上滚动
    print("向上滚动3次")

    pyautogui.scroll(-3)  # 向下滚动
    print("向下滚动3次")

    print("\n基础API演示完成!")

if __name__ == "__main__":
    basic_api_demo()

第2章 鼠标操作全面解析

2.1 鼠标移动方法详解

2.1.1 moveTo方法

moveTo()方法将鼠标移动到屏幕上的绝对坐标位置。

python 复制代码
import pyautogui

def moveTo_demo():
    """
    moveTo方法详解

    参数说明:
        x: 目标X坐标
        y: 目标Y坐标
        duration: 移动持续时间(秒),默认为0(瞬间移动)
        tween: 缓动函数,控制移动轨迹,默认为线性
    """

    # 基础用法:瞬间移动
    pyautogui.moveTo(100, 100)
    print("瞬间移动到 (100, 100)")

    # 带延迟的移动
    pyautogui.moveTo(200, 200, duration=1.0)
    print("1秒内移动到 (200, 200)")

    # 使用缓动函数
    pyautogui.moveTo(300, 300, duration=1.0, tween=pyautogui.easeInOutQuad)
    print("使用easeInOutQuad缓动函数移动到 (300, 300)")

    # 不同缓动函数对比
    positions = [
        (100, 100),
        (200, 100),
        (300, 100),
        (400, 100)
    ]

    tweens = [
        ('linear', pyautogui.linear),
        ('easeInQuad', pyautogui.easeInQuad),
        ('easeOutQuad', pyautogui.easeOutQuad),
        ('easeInOutQuad', pyautogui.easeInOutQuad)
    ]

    for i, (pos, (name, tween)) in enumerate(zip(positions, tweens)):
        pyautogui.moveTo(pos[0], pos[1], duration=0.5, tween=tween)
        print(f"使用 {name} 缓动函数移动到 {pos}")
2.1.2 move方法

move()方法相对于当前位置移动鼠标。

python 复制代码
import pyautogui

def move_demo():
    """
    move方法详解

    参数说明:
        xOffset: X轴相对移动距离(正数向右,负数向左)
        yOffset: Y轴相对移动距离(正数向下,负数向上)
        duration: 移动持续时间(秒)
        tween: 缓动函数
    """

    # 获取当前位置
    start_pos = pyautogui.position()
    print(f"起始位置: {start_pos}")

    # 相对移动
    pyautogui.move(100, 0, duration=0.5)
    print(f"向右移动100像素")

    pyautogui.move(0, 100, duration=0.5)
    print(f"向下移动100像素")

    pyautogui.move(-100, 0, duration=0.5)
    print(f"向左移动100像素")

    pyautogui.move(0, -100, duration=0.5)
    print(f"向上移动100像素")

    # 回到起始位置
    pyautogui.moveTo(start_pos[0], start_pos[1], duration=0.5)
    print(f"回到起始位置")

    # 绘制矩形轨迹
    print("\n绘制矩形轨迹:")
    rect_size = 50
    pyautogui.move(rect_size, 0, duration=0.3)      # 向右
    pyautogui.move(0, rect_size, duration=0.3)      # 向下
    pyautogui.move(-rect_size, 0, duration=0.3)     # 向左
    pyautogui.move(0, -rect_size, duration=0.3)     # 向上
    print("矩形绘制完成")
2.1.3 dragTo方法

dragTo()方法在按住鼠标左键的同时移动鼠标,用于拖拽操作。

python 复制代码
import pyautogui

def dragTo_demo():
    """
    dragTo方法详解

    参数说明:
        x: 目标X坐标
        y: 目标Y坐标
        duration: 拖拽持续时间(秒)
        button: 使用的鼠标按键,默认为'left'
        mouseDownUp: 是否执行按下和抬起操作,默认为True
        tween: 缓动函数
    """

    # 基础拖拽
    pyautogui.moveTo(100, 100, duration=0.5)
    pyautogui.dragTo(200, 200, duration=1.0)
    print("从 (100, 100) 拖拽到 (200, 200)")

    # 使用不同按键拖拽
    pyautogui.moveTo(100, 300, duration=0.5)
    pyautogui.dragTo(200, 400, duration=1.0, button='right')
    print("使用右键拖拽")

    # 不自动抬起按键
    pyautogui.moveTo(300, 100, duration=0.5)
    pyautogui.dragTo(400, 200, duration=1.0, mouseDownUp=False)
    print("拖拽但不抬起按键")
    pyautogui.mouseUp()  # 手动抬起按键
    print("手动抬起按键")
2.1.4 drag方法

drag()方法相对于当前位置进行拖拽操作。

python 复制代码
import pyautogui

def drag_demo():
    """
    drag方法详解

    参数说明:
        xOffset: X轴相对拖拽距离
        yOffset: Y轴相对拖拽距离
        duration: 拖拽持续时间(秒)
        button: 使用的鼠标按键
        mouseDownUp: 是否执行按下和抬起操作
        tween: 缓动函数
    """

    # 相对拖拽
    pyautogui.moveTo(100, 100, duration=0.5)
    pyautogui.drag(100, 100, duration=1.0)
    print("相对拖拽 (100, 100)")

    # 绘制圆形轨迹
    print("\n绘制圆形轨迹:")
    center_x, center_y = 300, 300
    radius = 50
    steps = 36

    pyautogui.moveTo(center_x + radius, center_y, duration=0.5)

    for i in range(steps):
        angle = (i + 1) * 360 / steps
        next_x = center_x + radius * (1 if i == 0 else 0)  # 简化计算
        next_y = center_y + radius * (1 if i == 0 else 0)

        # 计算下一个点
        import math
        next_x = center_x + radius * math.cos(math.radians(angle))
        next_y = center_y + radius * math.sin(math.radians(angle))

        # 相对拖拽
        current_x, current_y = pyautogui.position()
        dx = next_x - current_x
        dy = next_y - current_y

        if i == 0:
            pyautogui.mouseDown()
        else:
            pyautogui.drag(dx, dy, duration=0.1, mouseDownUp=False)

    pyautogui.mouseUp()
    print("圆形轨迹绘制完成")

2.2 缓动函数系统详解

缓动函数控制鼠标移动的轨迹和速度变化,使移动更加自然。

python 复制代码
import pyautogui
import math

def tween_functions_demo():
    """
    缓动函数详解

    PyAutoGUI提供多种缓动函数:
    - linear: 线性移动,速度恒定
    - easeInQuad: 加速移动
    - easeOutQuad: 减速移动
    - easeInOutQuad: 先加速后减速
    - easeInCubic: 三次加速
    - easeOutCubic: 三次减速
    - easeInOutCubic: 三次先加速后减速
    """

    # 定义测试位置
    start_y = 100
    positions = [
        (100, start_y),
        (200, start_y),
        (300, start_y),
        (400, start_y),
        (500, start_y),
        (600, start_y),
        (700, start_y)
    ]

    # 定义缓动函数
    tweens = [
        ('linear', pyautogui.linear),
        ('easeInQuad', pyautogui.easeInQuad),
        ('easeOutQuad', pyautogui.easeOutQuad),
        ('easeInOutQuad', pyautogui.easeInOutQuad),
        ('easeInCubic', pyautogui.easeInCubic),
        ('easeOutCubic', pyautogui.easeOutCubic),
        ('easeInOutCubic', pyautogui.easeInOutCubic)
    ]

    # 对比不同缓动函数
    print("对比不同缓动函数的效果:")
    for (pos, (name, tween)) in zip(positions, tweens):
        pyautogui.moveTo(pos[0], pos[1], duration=0.5, tween=tween)
        print(f"使用 {name} 移动到 {pos}")

    # 自定义缓动函数
    def custom_ease(n):
        """
        自定义缓动函数

        Args:
            n: 进度值,范围0.0到1.0

        Returns:
            float: 缓动后的值
        """
        # 自定义:先快速后缓慢
        return 1 - math.pow(1 - n, 3)

    # 使用自定义缓动函数
    pyautogui.moveTo(400, 300, duration=1.0, tween=custom_ease)
    print("使用自定义缓动函数移动")

# 缓动函数对比图
"""
缓动函数效果对比:

linear:        ████████████████████ (匀速)
easeInQuad:    ████████████████████ (加速)
easeOutQuad:   ████████████████████ (减速)
easeInOutQuad: ████████████████████ (先加速后减速)
"""
缓动函数应用场景
python 复制代码
import pyautogui

def tween_application_scenarios():
    """
    缓动函数应用场景
    """

    # 场景1:快速定位 - 使用linear
    print("场景1:快速定位")
    pyautogui.moveTo(100, 100, duration=0.2, tween=pyautogui.linear)
    print("快速移动到目标位置")

    # 场景2:自然移动 - 使用easeInOutQuad
    print("\n场景2:自然移动")
    pyautogui.moveTo(200, 200, duration=0.8, tween=pyautogui.easeInOutQuad)
    print("模拟人类自然的移动轨迹")

    # 场景3:精确控制 - 使用easeOutQuad
    print("\n场景3:精确控制")
    pyautogui.moveTo(300, 300, duration=1.0, tween=pyautogui.easeOutQuad)
    print("缓慢接近目标,提高精确度")

    # 场景4:游戏操作 - 使用easeInQuad
    print("\n场景4:游戏操作")
    pyautogui.moveTo(400, 400, duration=0.3, tween=pyautogui.easeInQuad)
    print("快速启动,适合游戏操作")

2.3 鼠标点击方法详解

2.3.1 click方法

click()方法是最常用的点击方法,支持多种参数配置。

python 复制代码
import pyautogui

def click_demo():
    """
    click方法详解

    参数说明:
        x: 目标X坐标(可选,默认为当前位置)
        y: 目标Y坐标(可选,默认为当前位置)
        clicks: 点击次数,默认为1
        interval: 点击间隔时间(秒),默认为0.0
        button: 鼠标按键,默认为'left',可选'right'、'middle'
        duration: 移动到目标位置的持续时间(秒)
        tween: 移动使用的缓动函数
    """

    # 基础点击
    pyautogui.click(100, 100)
    print("点击位置 (100, 100)")

    # 多次点击
    pyautogui.click(200, 200, clicks=3)
    print("点击位置 (200, 200) 3次")

    # 带间隔的多次点击
    pyautogui.click(300, 300, clicks=3, interval=0.2)
    print("点击位置 (300, 300) 3次,每次间隔0.2秒")

    # 右键点击
    pyautogui.click(400, 400, button='right')
    print("右键点击位置 (400, 400)")

    # 中键点击
    pyautogui.click(500, 500, button='middle')
    print("中键点击位置 (500, 500)")

    # 带移动的点击
    pyautogui.click(600, 600, duration=0.5)
    print("0.5秒内移动到 (600, 600) 并点击")

    # 当前位置点击
    pyautogui.click()
    print("点击当前位置")
2.3.2 其他点击方法
python 复制代码
import pyautogui

def other_click_methods():
    """
    其他点击方法详解
    """

    # rightClick - 右键点击
    pyautogui.rightClick(100, 100)
    print("右键点击 (100, 100)")

    # middleClick - 中键点击
    pyautogui.middleClick(200, 200)
    print("中键点击 (200, 200)")

    # doubleClick - 双击
    pyautogui.doubleClick(300, 300)
    print("双击 (300, 300)")

    # tripleClick - 三击
    pyautogui.tripleClick(400, 400)
    print("三击 (400, 400)")
2.3.3 tripleClick在文本选择中的应用
python 复制代码
import pyautogui
import time

def tripleclick_text_selection():
    """
    tripleClick在文本选择中的应用
    """

    # 模拟文本选择场景
    print("tripleClick文本选择演示:")

    # 假设有一个文本编辑器窗口
    # 1. 点击文本区域
    pyautogui.click(400, 300)
    time.sleep(0.5)

    # 2. 三击选择整行文本
    pyautogui.tripleClick(400, 300)
    print("三击选择整行文本")

    # 3. 可以复制选中的文本
    time.sleep(0.5)
    pyautogui.hotkey('ctrl', 'c')
    print("复制选中的文本")

    # 4. 在其他位置粘贴
    time.sleep(0.5)
    pyautogui.click(400, 400)
    pyautogui.hotkey('ctrl', 'v')
    print("粘贴文本")

2.4 鼠标滚轮操作详解

2.4.1 scroll方法
python 复制代码
import pyautogui

def scroll_demo():
    """
    scroll方法详解

    参数说明:
        clicks: 滚动次数(正数向上,负数向下)
        x: 滚动位置的X坐标(可选,默认为当前位置)
        y: 滚动位置的Y坐标(可选,默认为当前位置)
    """

    # 向上滚动
    pyautogui.moveTo(500, 300, duration=0.5)
    pyautogui.scroll(3)
    print("向上滚动3次")

    # 向下滚动
    pyautogui.scroll(-3)
    print("向下滚动3次")

    # 在指定位置滚动
    pyautogui.scroll(5, x=600, y=400)
    print("在 (600, 400) 位置向上滚动5次")

    # 大幅度滚动
    pyautogui.scroll(10)
    print("向上滚动10次")
2.4.2 vscroll和hscroll方法
python 复制代码
import pyautogui
import time

def vscroll_hscroll_demo():
    """
    vscroll和hscroll方法详解

    vscroll: 垂直滚动(与scroll相同)
    hscroll: 水平滚动
    """

    # 垂直滚动
    pyautogui.moveTo(500, 300, duration=0.5)
    pyautogui.vscroll(5)
    print("垂直滚动5次")

    # 水平滚动
    pyautogui.hscroll(5)
    print("水平滚动5次")

    # 组合滚动
    pyautogui.vscroll(3)
    pyautogui.hscroll(2)
    print("垂直滚动3次,水平滚动2次")

    # 在网页浏览中的应用
    print("\n网页浏览滚动演示:")
    # 向下滚动页面
    for i in range(5):
        pyautogui.vscroll(-3)
        time.sleep(0.5)
    print("向下滚动页面")

    # 水平滚动查看宽内容
    for i in range(3):
        pyautogui.hscroll(2)
        time.sleep(0.5)
    print("水平滚动查看宽内容")

2.5 鼠标位置获取与监控

python 复制代码
import pyautogui
import time

def mouse_position_monitoring():
    """
    鼠标位置获取与监控
    """

    # 获取当前位置
    current_pos = pyautogui.position()
    print(f"当前鼠标位置: {current_pos}")

    # 获取X和Y坐标
    x, y = pyautogui.position()
    print(f"X坐标: {x}, Y坐标: {y}")

    # 实时监控鼠标位置
    print("\n实时监控鼠标位置(5秒):")
    start_time = time.time()
    positions = []

    while time.time() - start_time < 5:
        pos = pyautogui.position()
        positions.append(pos)
        print(f"位置: {pos}")
        time.sleep(0.5)

    print(f"\n记录了 {len(positions)} 个位置点")

    # 位置记录与回放
    print("\n位置回放演示:")
    for pos in positions:
        pyautogui.moveTo(pos[0], pos[1], duration=0.1)
        time.sleep(0.2)
    print("位置回放完成")

    # 鼠标移动距离计算
    def calculate_distance(pos1, pos2):
        """计算两个位置之间的距离"""
        return ((pos2[0] - pos1[0])**2 + (pos2[1] - pos1[1])**2)**0.5

    if len(positions) > 1:
        total_distance = 0
        for i in range(len(positions) - 1):
            distance = calculate_distance(positions[i], positions[i+1])
            total_distance += distance

        print(f"鼠标移动总距离: {total_distance:.2f} 像素")

2.6 鼠标移动轨迹优化

python 复制代码
import pyautogui
import math

def mouse_trajectory_optimization():
    """
    鼠标移动轨迹优化
    """

    # 1. 绝对坐标与相对坐标混合使用
    print("绝对坐标与相对坐标混合使用:")
    start_pos = (100, 100)

    # 使用绝对坐标移动到起点
    pyautogui.moveTo(start_pos[0], start_pos[1], duration=0.5)

    # 使用相对坐标绘制图案
    pattern = [
        (50, 0),    # 向右
        (0, 50),    # 向下
        (-50, 0),   # 向左
        (0, -50)    # 向上
    ]

    for dx, dy in pattern:
        pyautogui.move(dx, dy, duration=0.3)
        print(f"相对移动 ({dx}, {dy})")

    # 2. 平滑曲线移动
    print("\n平滑曲线移动:")
    points = []
    for angle in range(0, 360, 10):
        x = 400 + 100 * math.cos(math.radians(angle))
        y = 300 + 100 * math.sin(math.radians(angle))
        points.append((x, y))

    for i, point in enumerate(points):
        if i == 0:
            pyautogui.moveTo(point[0], point[1], duration=0.5)
        else:
            pyautogui.moveTo(point[0], point[1], duration=0.1,
                           tween=pyautogui.easeInOutQuad)

    print("圆形轨迹绘制完成")

    # 3. 鼠标移动的精确控制
    print("\n鼠标移动的精确控制:")
    # 亚像素级移动(通过多次小步移动实现)
    target_x, target_y = 500, 500
    current_x, current_y = pyautogui.position()

    # 计算移动向量
    dx = target_x - current_x
    dy = target_y - current_y

    # 分10步移动
    steps = 10
    for i in range(steps):
        step_x = dx / steps
        step_y = dy / steps
        pyautogui.move(step_x, step_y, duration=0.05)
        print(f"步骤 {i+1}/{steps}: 移动 ({step_x:.1f}, {step_y:.1f})")

    print("精确移动完成")

2.7 实际应用场景

2.7.1 游戏自动化
python 复制代码
import pyautogui
import time

def game_automation():
    """
    游戏自动化示例
    """

    print("游戏自动化演示:")

    # 场景1:自动点击
    print("\n场景1:自动点击")
    click_positions = [(400, 300), (450, 350), (500, 400)]
    for pos in click_positions:
        pyautogui.click(pos[0], pos[1], duration=0.1)
        time.sleep(0.2)
    print("完成自动点击")

    # 场景2:技能连招
    print("\n场景2:技能连招")
    skill_keys = ['1', '2', '3', '4']
    for key in skill_keys:
        pyautogui.press(key)
        time.sleep(0.3)
    print("完成技能连招")

    # 场景3:鼠标拖拽
    print("\n场景3:鼠标拖拽")
    pyautogui.moveTo(300, 300, duration=0.3)
    pyautogui.dragTo(500, 500, duration=0.5, button='left')
    print("完成拖拽操作")
2.7.2 UI测试
python 复制代码
import pyautogui
import time

def ui_testing():
    """
    UI测试示例
    """

    print("UI测试演示:")

    # 场景1:按钮点击测试
    print("\n场景1:按钮点击测试")
    buttons = [
        (200, 200, "确定按钮"),
        (300, 200, "取消按钮"),
        (400, 200, "应用按钮")
    ]

    for x, y, name in buttons:
        pyautogui.click(x, y, duration=0.2)
        print(f"点击 {name}")
        time.sleep(0.5)

    # 场景2:菜单导航
    print("\n场景2:菜单导航")
    menu_items = [
        (100, 100, "文件"),
        (100, 150, "编辑"),
        (100, 200, "查看")
    ]

    for x, y, name in menu_items:
        pyautogui.moveTo(x, y, duration=0.2)
        pyautogui.click()
        print(f"打开 {name} 菜单")
        time.sleep(0.5)

    # 场景3:表单填写
    print("\n场景3:表单填写")
    form_fields = [
        (300, 300, "用户名"),
        (300, 350, "密码"),
        (300, 400, "邮箱")
    ]

    for x, y, field_name in form_fields:
        pyautogui.click(x, y, duration=0.2)
        pyautogui.write(f"test_{field_name}", interval=0.05)
        print(f"填写 {field_name} 字段")
        time.sleep(0.3)
2.7.3 批量操作
python 复制代码
import pyautogui
import time

def batch_operations():
    """
    批量操作示例
    """

    print("批量操作演示:")

    # 场景1:批量文件选择
    print("\n场景1:批量文件选择")
    file_positions = [
        (200, 200),
        (200, 250),
        (200, 300),
        (200, 350),
        (200, 400)
    ]

    # 按住Ctrl键选择多个文件
    pyautogui.keyDown('ctrl')
    for pos in file_positions:
        pyautogui.click(pos[0], pos[1])
        time.sleep(0.1)
    pyautogui.keyUp('ctrl')
    print("批量选择文件完成")

    # 场景2:批量数据处理
    print("\n场景2:批量数据处理")
    data_positions = [
        (400, 200),
        (400, 250),
        (400, 300)
    ]

    for pos in data_positions:
        pyautogui.click(pos[0], pos[1], duration=0.2)
        pyautogui.hotkey('ctrl', 'c')  # 复制
        time.sleep(0.2)
        pyautogui.click(600, 200)  # 粘贴位置
        pyautogui.hotkey('ctrl', 'v')  # 粘贴
        time.sleep(0.3)
    print("批量数据处理完成")

    # 场景3:批量截图
    print("\n场景3:批量截图")
    screenshot_regions = [
        (0, 0, 800, 600),
        (800, 0, 800, 600),
        (0, 600, 800, 600)
    ]

    for i, region in enumerate(screenshot_regions):
        screenshot = pyautogui.screenshot(region=region)
        screenshot.save(f"screenshot_{i+1}.png")
        print(f"保存截图 {i+1}")
        time.sleep(0.5)

第3章 键盘操作全面解析

3.1 键盘输入方法详解

3.1.1 typewrite方法

typewrite()方法用于输入文本字符串。

python 复制代码
import pyautogui

def typewrite_demo():
    """
    typewrite方法详解

    参数说明:
        message: 要输入的文本字符串
        interval: 每个字符之间的间隔时间(秒),默认为0.0
    """

    # 基础文本输入
    pyautogui.click(300, 300)  # 点击输入框
    pyautogui.typewrite('Hello World!')
    print("输入文本: Hello World!")

    # 带间隔的输入
    pyautogui.typewrite('With interval', interval=0.1)
    print("输入文本: With interval (每个字符间隔0.1秒)")

    # 输入多行文本
    pyautogui.typewrite('Line 1\nLine 2\nLine 3')
    print("输入多行文本")

    # 输入特殊字符
    pyautogui.typewrite('Special chars: @#$%^&*()')
    print("输入特殊字符")
3.1.2 write方法

write()方法是typewrite()的别名,功能完全相同。

python 复制代码
import pyautogui

def write_demo():
    """
    write方法详解
    """

    # write方法与typewrite方法功能相同
    pyautogui.click(300, 300)
    pyautogui.write('Using write method')
    print("使用write方法输入文本")

    # 带间隔的输入
    pyautogui.write('With interval', interval=0.05)
    print("带间隔输入文本")
3.1.3 interval参数精确控制技巧
python 复制代码
import pyautogui
import time

def interval_control_demo():
    """
    interval参数精确控制技巧
    """

    # 不同interval值的对比
    texts = [
        ("Fast typing", 0.01),
        ("Normal typing", 0.1),
        ("Slow typing", 0.2)
    ]

    for text, interval in texts:
        pyautogui.click(300, 300)
        pyautogui.write(text, interval=interval)
        print(f"输入 '{text}' (interval={interval})")
        time.sleep(1)

    # 动态调整interval
    print("\n动态调整interval:")
    text = "Dynamic interval typing"
    for i, char in enumerate(text):
        # 前半部分快速,后半部分慢速
        current_interval = 0.02 if i < len(text) // 2 else 0.1
        pyautogui.write(char, interval=current_interval)
    print("完成动态间隔输入")

    # 模拟人类打字节奏
    print("\n模拟人类打字节奏:")
    human_text = "Human like typing"
    for char in human_text:
        # 随机间隔,模拟人类打字的不规律性
        import random
        random_interval = random.uniform(0.05, 0.15)
        pyautogui.write(char, interval=random_interval)
    print("完成人类节奏输入")
3.1.4 特殊字符处理与转义
python 复制代码
import pyautogui
import time

def special_characters_demo():
    """
    特殊字符处理与转义
    """

    # 输入特殊符号
    special_chars = "!@#$%^&*()_+-=[]{}|;':\",./<>?"
    pyautogui.click(300, 300)
    pyautogui.write(special_chars)
    print(f"输入特殊字符: {special_chars}")

    # 输入Unicode字符
    unicode_chars = "中文 日本語 한국어"
    pyautogui.write(unicode_chars)
    print(f"输入Unicode字符: {unicode_chars}")

    # 转义字符处理
    escape_chars = {
        '\n': '换行',
        '\t': '制表符',
        '\\': '反斜杠',
        '\"': '双引号',
        '\'': '单引号'
    }

    print("\n转义字符处理:")
    for char, description in escape_chars.items():
        pyautogui.write(char)
        print(f"输入 {description}")
        time.sleep(0.5)
3.1.5 修饰键处理
python 复制代码
import pyautogui

def modifier_keys_demo():
    """
    修饰键处理
    """

    # 大写字母(Shift键)
    pyautogui.click(300, 300)
    pyautogui.write('UPPERCASE')  # 自动处理大写
    print("输入大写字母")

    # 使用Shift键
    pyautogui.keyDown('shift')
    pyautogui.write('lowercase becomes uppercase')
    pyautogui.keyUp('shift')
    print("使用Shift键输入大写")

    # 组合修饰键
    pyautogui.keyDown('ctrl')
    pyautogui.keyDown('shift')
    pyautogui.write('a')  # Ctrl+Shift+A
    pyautogui.keyUp('shift')
    pyautogui.keyUp('ctrl')
    print("使用Ctrl+Shift组合键")
3.1.6 键盘输入unicode字符处理
python 复制代码
import pyautogui

def unicode_input_demo():
    """
    键盘输入unicode字符处理
    """

    # 直接输入Unicode字符
    unicode_texts = [
        "Hello 世界",
        "こんにちは 世界",
        "안녕하세요 세계",
        "مرحبا بالعالم"
    ]

    for text in unicode_texts:
        pyautogui.click(300, 300)
        pyautogui.write(text)
        print(f"输入Unicode文本: {text}")
        time.sleep(1)

    # 使用Unicode码点输入
    print("\n使用Unicode码点:")
    # 注意:PyAutoGUI的write方法直接支持Unicode字符
    # 不需要使用码点方式
    special_unicode = "★☆♥♦♣♠"
    pyautogui.write(special_unicode)
    print(f"输入特殊Unicode字符: {special_unicode}")

3.2 特殊键与组合键操作

3.2.1 press方法

press()方法用于按下单个按键。

python 复制代码
import pyautogui

def press_demo():
    """
    press方法详解

    参数说明:
        key: 按键名称
        presses: 按键次数,默认为1
        interval: 按键间隔时间(秒),默认为0.0
    """

    # 基础按键
    pyautogui.press('enter')
    print("按下回车键")

    pyautogui.press('space')
    print("按下空格键")

    pyautogui.press('tab')
    print("按下Tab键")

    # 多次按键
    pyautogui.press('backspace', presses=5)
    print("按下退格键5次")

    # 带间隔的多次按键
    pyautogui.press('right', presses=10, interval=0.1)
    print("按下右箭头键10次,每次间隔0.1秒")

    # 功能键
    function_keys = ['f1', 'f5', 'f11']
    for key in function_keys:
        pyautogui.press(key)
        print(f"按下 {key} 键")
        time.sleep(0.5)
3.2.2 presses参数
python 复制代码
import pyautogui

def presses_parameter_demo():
    """
    presses参数详解
    """

    # 使用presses参数重复按键
    pyautogui.press('a', presses=5)
    print("按下'a'键5次")

    # 带间隔的重复按键
    pyautogui.press('b', presses=3, interval=0.2)
    print("按下'b'键3次,每次间隔0.2秒")

    # 实际应用:删除多个字符
    pyautogui.press('backspace', presses=10, interval=0.05)
    print("删除10个字符")

    # 实际应用:移动光标
    pyautogui.press('right', presses=5)
    print("向右移动光标5次")
3.2.3 keyDown和keyUp方法
python 复制代码
import pyautogui

def keydown_keyup_demo():
    """
    keyDown和keyUp方法详解
    """

    # 基础用法
    pyautogui.keyDown('shift')
    pyautogui.write('hello')  # 输入大写
    pyautogui.keyUp('shift')
    print("使用Shift键输入大写字母")

    # 长按按键
    pyautogui.keyDown('a')
    time.sleep(1)  # 按住1秒
    pyautogui.keyUp('a')
    print("长按'a'键1秒")

    # 组合按键
    pyautogui.keyDown('ctrl')
    pyautogui.keyDown('c')
    pyautogui.keyUp('c')
    pyautogui.keyUp('ctrl')
    print("执行Ctrl+C复制操作")

    # 注意:确保按键成对出现
    try:
        pyautogui.keyDown('ctrl')
        # 执行一些操作
        pyautogui.press('v')
    finally:
        pyautogui.keyUp('ctrl')  # 确保释放按键
3.2.4 常用键名列表
python 复制代码
import pyautogui

def common_key_names_demo():
    """
    常用键名列表与使用
    """

    # 字母键
    letter_keys = ['a', 'b', 'c', 'd', 'e']
    for key in letter_keys:
        pyautogui.press(key)
    print("输入字母键")

    # 数字键
    number_keys = ['1', '2', '3', '4', '5']
    for key in number_keys:
        pyautogui.press(key)
    print("输入数字键")

    # 功能键
    function_keys = ['f1', 'f2', 'f3', 'f4', 'f5']
    for key in function_keys:
        pyautogui.press(key)
    print("输入功能键")

    # 特殊键
    special_keys = {
        'enter': '回车',
        'space': '空格',
        'tab': 'Tab',
        'backspace': '退格',
        'delete': '删除',
        'escape': 'Esc',
        'home': 'Home',
        'end': 'End',
        'pageup': 'PageUp',
        'pagedown': 'PageDown'
    }

    for key, description in special_keys.items():
        pyautogui.press(key)
        print(f"按下 {description} 键")
        time.sleep(0.3)

    # 方向键
    arrow_keys = ['up', 'down', 'left', 'right']
    for key in arrow_keys:
        pyautogui.press(key)
        print(f"按下方向键: {key}")
        time.sleep(0.3)

3.3 热键操作详解

3.3.1 hotkey方法

hotkey()方法用于执行组合键操作。

python 复制代码
import pyautogui

def hotkey_demo():
    """
    hotkey方法详解

    参数说明:
        *keys: 多个按键名称,按顺序按下
        interval: 按键之间的间隔时间(秒),默认为0.0
    """

    # 基础热键
    pyautogui.hotkey('ctrl', 'c')
    print("执行 Ctrl+C 复制")

    pyautogui.hotkey('ctrl', 'v')
    print("执行 Ctrl+V 粘贴")

    pyautogui.hotkey('ctrl', 'a')
    print("执行 Ctrl+A 全选")

    # 三键组合
    pyautogui.hotkey('ctrl', 'shift', 'a')
    print("执行 Ctrl+Shift+A")

    # 带间隔的热键
    pyautogui.hotkey('ctrl', 'alt', 'delete', interval=0.1)
    print("执行 Ctrl+Alt+Delete")

    # 常用热键组合
    common_hotkeys = [
        (['ctrl', 's'], '保存'),
        (['ctrl', 'z'], '撤销'),
        (['ctrl', 'y'], '重做'),
        (['ctrl', 'f'], '查找'),
        (['ctrl', 'p'], '打印')
    ]

    for keys, description in common_hotkeys:
        pyautogui.hotkey(*keys)
        print(f"执行 {description}")
        time.sleep(0.5)
3.3.2 delay参数
python 复制代码
import pyautogui

def delay_parameter_demo():
    """
    delay参数详解
    """

    # 使用delay参数控制按键间隔
    pyautogui.hotkey('ctrl', 'alt', 'delete', interval=0.2)
    print("执行 Ctrl+Alt+Delete (间隔0.2秒)")

    # 对比不同delay值
    delays = [0.05, 0.1, 0.2]
    for delay in delays:
        pyautogui.hotkey('ctrl', 'c', interval=delay)
        print(f"执行 Ctrl+C (间隔{delay}秒)")
        time.sleep(0.5)

    # 实际应用:快速连续热键
    print("\n快速连续热键:")
    hotkey_sequence = [
        ['ctrl', 'c'],
        ['ctrl', 'v'],
        ['ctrl', 'a'],
        ['ctrl', 'c']
    ]

    for keys in hotkey_sequence:
        pyautogui.hotkey(*keys, interval=0.1)
        time.sleep(0.3)
    print("完成快速连续热键操作")

3.4 键盘事件模拟与延迟控制

3.4.1 PAUSE全局设置
python 复制代码
import pyautogui
import time

def pause_global_setting():
    """
    PAUSE全局设置详解
    """

    # 获取当前PAUSE设置
    print(f"当前PAUSE设置: {pyautogui.PAUSE}")

    # 设置全局延迟
    pyautogui.PAUSE = 0.5
    print("设置全局延迟为0.5秒")

    # 测试全局延迟
    start_time = time.time()
    pyautogui.write('test')
    end_time = time.time()
    print(f"实际延迟: {end_time - start_time:.2f}秒")

    # 恢复默认设置
    pyautogui.PAUSE = 0.1
    print("恢复全局延迟为0.1秒")
3.4.2 _pause参数
python 复制代码
import pyautogui
import time

def _pause_parameter_demo():
    """
    _pause参数详解
    """

    # _pause参数控制是否在每个操作后暂停
    # 注意:这是一个内部参数,通常不需要手动设置

    # 禁用暂停
    pyautogui._pause = False
    print("禁用操作间暂停")

    # 执行快速操作
    start_time = time.time()
    for i in range(5):
        pyautogui.write('a')
    end_time = time.time()
    print(f"5次写入耗时: {end_time - start_time:.2f}秒")

    # 启用暂停
    pyautogui._pause = True
    print("启用操作间暂停")

    # 执行带暂停的操作
    start_time = time.time()
    for i in range(5):
        pyautogui.write('b')
    end_time = time.time()
    print(f"5次写入耗时: {end_time - start_time:.2f}秒")
3.4.3 自定义延迟策略
python 复制代码
import pyautogui
import time

def custom_delay_strategy():
    """
    自定义延迟策略
    """

    # 策略1:根据操作类型设置不同延迟
    def operation_with_delay(operation, delay_map):
        """
        根据操作类型应用不同延迟

        Args:
            operation: 操作函数
            delay_map: 延迟映射字典
        """
        operation()
        op_type = operation.__name__
        if op_type in delay_map:
            time.sleep(delay_map[op_type])

    # 定义延迟映射
    delay_map = {
        'write': 0.05,
        'press': 0.1,
        'hotkey': 0.15
    }

    # 应用自定义延迟
    operation_with_delay(lambda: pyautogui.write('test'), delay_map)
    operation_with_delay(lambda: pyautogui.press('enter'), delay_map)
    operation_with_delay(lambda: pyautogui.hotkey('ctrl', 'c'), delay_map)

    # 策略2:动态调整延迟
    def adaptive_delay(base_delay, complexity):
        """
        根据操作复杂度动态调整延迟

        Args:
            base_delay: 基础延迟
            complexity: 复杂度因子(1-10)
        """
        return base_delay * complexity

    # 应用动态延迟
    operations = [
        (lambda: pyautogui.write('simple'), 1),
        (lambda: pyautogui.write('complex'), 3),
        (lambda: pyautogui.hotkey('ctrl', 'c'), 5)
    ]

    for operation, complexity in operations:
        operation()
        delay = adaptive_delay(0.05, complexity)
        time.sleep(delay)
        print(f"操作复杂度: {complexity}, 延迟: {delay:.2f}秒")

    # 策略3:基于系统负载调整延迟
    def system_aware_delay():
        """
        基于系统负载调整延迟
        """
        try:
            import psutil
            cpu_usage = psutil.cpu_percent()
        except ImportError:
            cpu_usage = 50  # 默认值

        if cpu_usage > 80:
            return 0.2  # 高负载时增加延迟
        elif cpu_usage > 50:
            return 0.1  # 中等负载
        else:
            return 0.05  # 低负载

    # 应用系统感知延迟
    for i in range(3):
        pyautogui.write(f'line {i}\n')
        delay = system_aware_delay()
        time.sleep(delay)
        print(f"延迟: {delay:.2f}秒")

3.5 实际应用场景

3.5.1 表单填写
python 复制代码
import pyautogui
import time

def form_filling():
    """
    表单填写自动化
    """

    print("表单填写演示:")

    # 表单字段数据
    form_data = {
        'username': 'testuser',
        'password': 'password123',
        'email': 'test@example.com',
        'phone': '1234567890'
    }

    # 表单字段位置(假设)
    field_positions = {
        'username': (300, 200),
        'password': (300, 250),
        'email': (300, 300),
        'phone': (300, 350)
    }

    # 填写表单
    for field_name, value in form_data.items():
        x, y = field_positions[field_name]
        pyautogui.click(x, y, duration=0.2)
        pyautogui.write(value, interval=0.05)
        print(f"填写 {field_name}: {value}")
        time.sleep(0.3)

    # 提交表单
    pyautogui.click(400, 400)
    print("提交表单")
3.5.2 快捷键操作
python 复制代码
import pyautogui

def shortcut_operations():
    """
    快捷键操作自动化
    """

    print("快捷键操作演示:")

    # 文本编辑快捷键
    text_shortcuts = [
        (['ctrl', 'a'], '全选'),
        (['ctrl', 'c'], '复制'),
        (['ctrl', 'v'], '粘贴'),
        (['ctrl', 'x'], '剪切'),
        (['ctrl', 'z'], '撤销')
    ]

    for keys, description in text_shortcuts:
        pyautogui.hotkey(*keys)
        print(f"执行 {description}")
        time.sleep(0.5)

    # 浏览器快捷键
    browser_shortcuts = [
        (['ctrl', 't'], '新标签页'),
        (['ctrl', 'w'], '关闭标签页'),
        (['ctrl', 'tab'], '切换标签页'),
        (['ctrl', 'l'], '地址栏')
    ]

    for keys, description in browser_shortcuts:
        pyautogui.hotkey(*keys)
        print(f"执行 {description}")
        time.sleep(0.5)
3.5.3 文本输入
python 复制代码
import pyautogui

def text_input_demo():
    """
    文本输入自动化
    """

    print("文本输入演示:")

    # 场景1:输入长文本
    long_text = """
    This is a long text example.
    It contains multiple lines.
    And various punctuation marks!
    """

    pyautogui.click(300, 300)
    pyautogui.write(long_text, interval=0.02)
    print("输入长文本")

    # 场景2:输入格式化文本
    formatted_text = "Name: John Doe\nAge: 30\nCity: New York"
    pyautogui.write(formatted_text)
    print("输入格式化文本")

    # 场景3:输入代码
    code_snippet = """
    def hello_world():
        print('Hello, World!')
        return True
    """

    pyautogui.write(code_snippet, interval=0.01)
    print("输入代码片段")

相关推荐
Spliceㅤ2 小时前
项目:基于qwen的点餐系统
开发语言·人工智能·python·机器学习·自然语言处理
asdzx672 小时前
使用 Python 快速为 PDF 添加背景色或背景图片
python·pdf
badhope2 小时前
Docker入门到实战全攻略
linux·python·docker·github·matplotlib
华研前沿标杆游学3 小时前
2026深圳企业参访-走进深圳华星光电TCL学习智能制造
python
dapeng28703 小时前
Python异步编程入门:Asyncio库的使用
jvm·数据库·python
2401_851272993 小时前
Python面向对象编程(OOP)终极指南
jvm·数据库·python
2401_831824963 小时前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
Liu628883 小时前
NumPy入门:高性能科学计算的基础
jvm·数据库·python
文艺小码农3 小时前
pytorch(GPU版)安装教程
人工智能·pytorch·python
浮生札记3 小时前
腾讯云 COS STS 临时密钥上传
python·腾讯云·fastapi·对象存储