从入门到精通详解Python键盘鼠标自动化库
作者:小庄-Python办公
在自动化测试、办公自动化、游戏脚本等场景中,我们经常需要模拟键盘鼠标操作,本文将详细介绍几个跑一趟红包主流的键盘鼠标操作库,帮助你选择最适合的工具
前言
在自动化测试、办公自动化、游戏脚本等场景中,我们经常需要模拟键盘鼠标操作。Python提供了多个强大的库来实现这些功能。本文将详细介绍几个主流的键盘鼠标操作库,帮助你选择最适合的工具。
1. PyAutoGUI - 跨平台GUI自动化利器
PyAutoGUI是最受欢迎的跨平台GUI自动化库之一,支持Windows、macOS和Linux系统。
安装
pip install pyautogui
主要特性
- 跨平台支持(Windows、macOS、Linux)
- 支持鼠标移动、点击、拖拽等操作
- 支持键盘输入、快捷键等操作
- 提供截图和图像识别功能
- 内置安全保护机制(fail-safe)
鼠标操作示例
import pyautogui
import time
# 设置暂停时间,给操作留出缓冲
pyautogui.PAUSE = 1
# 获取屏幕尺寸
screen_width, screen_height = pyautogui.size()
print(f"屏幕尺寸: {screen_width}x{screen_height}")
# 移动鼠标到指定位置
pyautogui.moveTo(100, 100, duration=1) # 持续1秒移动到(100,100)
# 相对移动
pyautogui.moveRel(50, 50, duration=0.5) # 相对当前位置移动50,50
# 鼠标点击
pyautogui.click(200, 200) # 在(200,200)位置单击
pyautogui.doubleClick(300, 300) # 双击
pyautogui.rightClick(400, 400) # 右键单击
# 鼠标拖拽
pyautogui.dragTo(500, 500, duration=1) # 拖拽到指定位置
pyautogui.dragRel(100, 0, duration=0.5) # 相对拖拽
# 滚动鼠标
pyautogui.scroll(500) # 向上滚动500个单位
pyautogui.scroll(-500) # 向下滚动500个单位
键盘操作示例
# 输入文本
pyautogui.typewrite('Hello World!', interval=0.1) # 每个字符间隔0.1秒
# 按键操作
pyautogui.press('enter') # 按回车键
pyautogui.press(['ctrl', 'a']) # 组合键Ctrl+A
# 热键操作
pyautogui.hotkey('ctrl', 'c') # Ctrl+C复制
pyautogui.hotkey('ctrl', 'v') # Ctrl+V粘贴
# 按键事件
pyautogui.keyDown('shift') # 按下Shift
pyautogui.typewrite('hello') # 输入大写HELLO
pyautogui.keyUp('shift') # 释放Shift
安全保护机制
PyAutoGUI内置了fail-safe保护机制:
# 启用fail-safe模式(默认开启) pyautogui.FAILSAFE = True # 当鼠标移动到屏幕左上角时会触发FailSafeException # 这可以防止程序失控
2. pynput - 更精细的控制
pynput提供了更底层的键盘鼠标控制,适合需要精细控制的场景。
安装
pip install pynput
鼠标控制
from pynput.mouse import Button, Controller
import time
mouse = Controller()
# 获取当前鼠标位置
print(f"当前位置: {mouse.position}")
# 设置鼠标位置
mouse.position = (500, 500)
# 相对移动
mouse.move(50, -50)
# 鼠标点击
mouse.click(Button.left, 1) # 左键单击
mouse.click(Button.right, 2) # 右键双击
mouse.click(Button.middle, 1) # 中键单击
# 按下和释放
mouse.press(Button.left)
time.sleep(0.1)
mouse.release(Button.left)
# 滚动
mouse.scroll(0, 5) # 向上滚动5个单位
键盘控制
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
# 输入文本
keyboard.type('Hello World!')
# 按键操作
keyboard.press(Key.space)
keyboard.release(Key.space)
# 组合键
with keyboard.pressed(Key.ctrl):
keyboard.press('a')
keyboard.release('a')
# 功能键
keyboard.press(Key.enter)
keyboard.release(Key.enter)
# 特殊按键
keyboard.press(Key.f1)
keyboard.release(Key.f1)
监听功能(PyAutoGUI不具备)
from pynput import mouse, keyboard
def on_move(x, y):
print(f"鼠标移动到: ({x}, {y})")
def on_click(x, y, button, pressed):
print(f"{'按下' if pressed else '释放'} {button} 在 ({x}, {y})")
if not pressed:
# 停止监听
return False
def on_scroll(x, y, dx, dy):
print(f"鼠标滚动在 ({x}, {y}),滚动量: ({dx}, {dy})")
# 设置鼠标监听
with mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll) as listener:
listener.join()
def on_press(key):
try:
print(f"按下字母键: {key.char}")
except AttributeError:
print(f"按下特殊键: {key}")
def on_release(key):
print(f"释放: {key}")
if key == keyboard.Key.esc:
# 按ESC键停止监听
return False
# 设置键盘监听
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
3. keyboard - 专注键盘操作
keyboard库专注于键盘操作,提供了更简单的API。
安装
pip install keyboard
基本用法
import keyboard
import time
# 输入文本
keyboard.write('Hello World!')
# 按键操作
keyboard.press_and_release('enter')
keyboard.press_and_release('ctrl+a')
# 等待按键
keyboard.wait('esc') # 等待ESC键被按下
# 检查按键状态
if keyboard.is_pressed('ctrl'):
print("Ctrl键被按下")
# 添加热键
keyboard.add_hotkey('ctrl+shift+a', lambda: print('热键被触发!'))
# 记录按键
recorded = keyboard.record(until='esc')
keyboard.play(recorded) # 重放记录的按键
# 发送组合键
keyboard.send('ctrl+shift+esc') # 打开任务管理器
4. 各库对比分析
| 特性 | PyAutoGUI | pynput | keyboard |
|---|---|---|---|
| 跨平台 | ✅ | ✅ | ✅ |
| 鼠标控制 | ✅ | ✅ | ❌ |
| 键盘控制 | ✅ | ✅ | ✅ |
| 监听功能 | ❌ | ✅ | ✅ |
| 图像识别 | ✅ | ❌ | ❌ |
| 易用性 | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 精细控制 | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| 文档完善度 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
5. 实际应用场景
办公自动化
import pyautogui
import time
def auto_fill_form():
"""自动填写表格"""
time.sleep(3) # 给用户时间切换到目标窗口
# 填写姓名
pyautogui.click(300, 200)
pyautogui.typewrite('张三')
# 填写邮箱
pyautogui.press('tab')
pyautogui.typewrite('zhangsan@example.com')
# 选择下拉框
pyautogui.press('tab')
pyautogui.press('down')
pyautogui.press('enter')
# 提交表单
pyautogui.press('tab')
pyautogui.press('enter')
自动化测试
from pynput.mouse import Button, Controller
from pynput.keyboard import Key, Controller as KeyboardController
import time
class AutoTester:
def __init__(self):
self.mouse = Controller()
self.keyboard = KeyboardController()
def test_login(self):
"""测试登录功能"""
# 点击用户名输入框
self.mouse.position = (400, 300)
self.mouse.click(Button.left, 1)
# 输入用户名
self.keyboard.type('testuser')
# 切换到密码框
self.keyboard.press(Key.tab)
self.keyboard.release(Key.tab)
# 输入密码
self.keyboard.type('password123')
# 点击登录按钮
self.mouse.position = (450, 400)
self.mouse.click(Button.left, 1)
# 等待响应
time.sleep(2)
# 这里可以添加断言逻辑
print("登录测试完成")
游戏脚本
import pyautogui
import time
import random
def auto_click_game():
"""自动点击游戏"""
print("3秒后开始自动点击,按Ctrl+C停止")
time.sleep(3)
try:
while True:
# 在随机位置点击
x = random.randint(100, 700)
y = random.randint(100, 500)
pyautogui.click(x, y)
# 随机等待时间
wait_time = random.uniform(0.1, 0.5)
time.sleep(wait_time)
except KeyboardInterrupt:
print("\n自动点击已停止")
6. 注意事项和最佳实践
1. 安全保护
# 始终启用fail-safe保护 pyautogui.FAILSAFE = True # 设置适当的延迟 pyautogui.PAUSE = 0.5
2. 异常处理
try:
# 自动化操作
pyautogui.click(100, 100)
pyautogui.typewrite('Hello')
except pyautogui.FailSafeException:
print("Fail-safe被触发,程序停止")
except Exception as e:
print(f"发生错误: {e}")
3. 多显示器支持
# PyAutoGUI目前只支持主显示器 # 如果需要支持多显示器,可以考虑使用其他库 # 或者使用pygetwindow等库来管理窗口
4. 权限问题
# 在某些系统上需要管理员权限 # macOS需要在系统偏好设置中允许辅助功能 # Linux可能需要安装额外的依赖
7. 总结
选择合适的库取决于你的具体需求:
- PyAutoGUI:最适合需要跨平台GUI自动化的场景,功能全面,文档完善
- pynput:适合需要精细控制或监听输入的场景,提供更底层的接口
- keyboard:专注键盘操作,API简单直观,适合键盘相关的自动化
无论选择哪个库,都要注意安全性和稳定性,合理使用延迟和异常处理,确保自动化脚本的可靠性。
到此这篇关于从入门到精通详解Python键盘鼠标自动化库的文章就介绍到这了,更多相关Python键盘鼠标自动化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
