本文目录导读:

- 使用现成软件(零门槛)
- 使用 Python +
pynput或pyautogui(最灵活,推荐) - 使用 AutoHotkey (AHK) —— Windows 利器
- 专业测试工具(Selenium / Appium / WinAppDriver)
- 总结建议
录制和回放键鼠动作是自动化测试、游戏脚本或重复性办公操作中的常见需求,根据你的使用场景(是普通办公、游戏还是专业测试),有几种不同的实现方式。
以下我将分别介绍 使用现成软件(最简单)、使用编程语言(Python) 和 使用AutoHotkey(AHK,适合Windows) 的方法。
使用现成软件(零门槛)
这种方法不需要编写代码,适合临时性或简单重复操作。
-
TinyTask(重量极轻,纯绿色):
- 原理:直接录制鼠标点击和键盘输入。
- 操作:点击“Record” -> 做一遍动作 -> 点击“Stop” -> 点击“Play”回放。
- 优点:不到100KB,无需安装,简单粗暴。
- 缺点:只能按固定坐标点击,窗口移动后就会失效。
-
AutoClick(开源):
适合单纯的鼠标连点。
-
Quicker / 按键精灵:
- 按键精灵:国内最知名的键鼠录制软件,支持“找图”、“找色”功能,可以解决窗口移动问题。
- Quicker:更现代的效率工具,支持“鼠标动作”录制脚本。
使用 Python + pynput 或 pyautogui(最灵活,推荐)
这种方法适合开发人员,或者需要精确控制、可编辑脚本的场景。
核心思路:
- 录制:监听鼠标事件(移动、点击)和键盘事件,并记录成列表。
- 回放:读取列表,模拟鼠标移动、按下/释放、键盘点击。
示例代码(使用 pynput)
第一步:安装库
pip install pynput
第二步:录制脚本 (record.py)
这个脚本会记录你的键鼠动作,并在按下 F8 键时停止录制,并将数据保存到 actions.txt 文件。
from pynput import mouse, keyboard
import time
import json
# 存储录制的事件
recorded_actions = []
start_time = time.time()
recording = True
def on_move(x, y):
if recording:
recorded_actions.append({
"type": "move",
"x": x,
"y": y,
"time": time.time() - start_time
})
def on_click(x, y, button, pressed):
if recording:
recorded_actions.append({
"type": "click",
"x": x,
"y": y,
"button": str(button),
"pressed": pressed,
"time": time.time() - start_time
})
# 如果按下的是鼠标右键并且已经停止(防止干扰),但这里我们保持录制
if not recording:
return False
def on_press(key):
global recording
if recording:
try:
# 录制普通按键
recorded_actions.append({
"type": "keyboard",
"key": key.char,
"pressed": True,
"time": time.time() - start_time
})
except AttributeError:
# 录制特殊按键(如 Ctrl, Alt, F1 等)
recorded_actions.append({
"type": "keyboard",
"key": str(key),
"pressed": True,
"time": time.time() - start_time
})
def on_release(key):
if recording:
try:
recorded_actions.append({
"type": "keyboard",
"key": key.char,
"pressed": False,
"time": time.time() - start_time
})
except AttributeError:
recorded_actions.append({
"type": "keyboard",
"key": str(key),
"pressed": False,
"time": time.time() - start_time
})
# 设置热键 F8 停止录制
def on_activate_hotkey():
global recording
print("F8 按下,停止录制...")
recording = False
# 保存到文件
with open("actions.txt", "w") as f:
json.dump(recorded_actions, f, indent=2)
print(f"录制完成,共 {len(recorded_actions)} 个动作,已保存至 actions.txt")
# 停止监听
return False
# 监听热键
hotkey_listener = keyboard.GlobalHotKeys({
'<f8>': on_activate_hotkey
})
# 启动监听
print("开始录制... 按 F8 停止。")
mouse_listener = mouse.Listener(on_move=on_move, on_click=on_click)
keyboard_listener = keyboard.Listener(on_press=on_press, on_release=on_release)
mouse_listener.start()
keyboard_listener.start()
hotkey_listener.start()
keyboard_listener.join()
mouse_listener.join()
第三步:回放脚本 (playback.py)
这个脚本会读取 actions.txt 并按照时间差模拟执行。
from pynput.mouse import Button, Controller as MouseController
from pynput.keyboard import Key, Controller as KeyboardController
import time
import json
mouse = MouseController()
keyboard = KeyboardController()
def play_actions(file_path="actions.txt"):
with open(file_path, "r") as f:
actions = json.load(f)
print(f"开始回放 {len(actions)} 个动作...")
# 等待5秒,让你有机会切换到目标窗口
for i in range(5, 0, -1):
print(f"将在 {i} 秒后开始... 请切换到目标窗口。")
time.sleep(1)
start_time = time.time()
for action in actions:
# 等待精确的时间间隔
delay = action["time"]
time.sleep(delay - (time.time() - start_time) + 0.001) # 微小补偿
if action["type"] == "move":
mouse.position = (action["x"], action["y"])
elif action["type"] == "click":
mouse.position = (action["x"], action["y"])
button = Button.left if "left" in action["button"] else Button.right
if action["pressed"]:
mouse.press(button)
else:
mouse.release(button)
elif action["type"] == "keyboard":
key = action["key"]
# 处理普通字符和特殊按键
if action["pressed"]:
if len(key) == 1:
keyboard.press(key)
else:
# 特殊按键:Key.xxx
special_key = getattr(Key, key.replace("Key.", ""), None)
if special_key:
keyboard.press(special_key)
else:
if len(key) == 1:
keyboard.release(key)
else:
special_key = getattr(Key, key.replace("Key.", ""), None)
if special_key:
keyboard.release(special_key)
print("回放完成。")
if __name__ == "__main__":
play_actions()
使用方法:
- 运行
record.py。 - 执行你要录制的操作。
- 按下
F8停止录制。 - 打开目标窗口(确保布局和目标程序一致)。
- 运行
playback.py,脚本会在5秒倒计时后开始回放。
使用 AutoHotkey (AHK) —— Windows 利器
AHK 是 Windows 上最强大的自动化脚本语言之一,可以录制并生成可执行的 .ahk 脚本。
推荐工具:TinyTask 或 Pulover‘s Macro Creator。
- Pulover’s Macro Creator:
- 下载并运行软件。
- 点击 “Record” -> 开始操作 -> 停止。
- 软件会自动生成 AHK 脚本代码,你可以点击 “Play” 回放,或 “Export” 保存为
.ahk脚本。
优点:
- 支持图像识别:可以找图找色,不受固定坐标限制。
- 生成的脚本小巧:适合长期使用。
自己写 AHK 脚本(录制回放):
; 录制脚本
RecordMacro(FileName) {
KeyHistory ; 启用键鼠历史记录
Settimer, SaveMacro, Off
Loop {
Input, Key, L1, {F8} ; 按下 F8 停止
if (ErrorLevel != "EndKey:") {
FileAppend, % Key . "`n", % FileName
}
}
}
; 回放脚本(简化版,需要先录制到文件里)
F9::
Loop, read, C:\MyMacro.txt
{
SendInput, %A_LoopReadLine%
Sleep, 100 ; 添加延迟
}
return
专业测试工具(Selenium / Appium / WinAppDriver)
如果你是做 Web 自动化 或 桌面应用测试,上述方法不够稳定(容易受布局变化影响)。
- Selenium IDE:浏览器插件,录制网页操作,导出为各种语言脚本。
- Appium Inspector:录制移动端操作。
- WinAppDriver:录制 Windows 桌面应用测试。
总结建议
| 使用场景 | 推荐方案 | 难度 |
|---|---|---|
| 一次性的、简单的重复操作 | TinyTask / 按键精灵 | ⭐ |
| 需要长期使用、可编辑 | Python + pynput |
⭐⭐⭐ |
| Windows 重度用户、游戏 | AutoHotkey (AHK) / Pulover‘s Macro Creator | ⭐⭐ |
| 网页测试 | Selenium IDE | ⭐ |
| 游戏脚本(需要截图/图像识别) | 按键精灵 / Python + pyautogui + opencv |
⭐⭐⭐⭐ |
重要提示:
- 大多数游戏都禁止使用这类脚本进行自动操作(违反用户协议)。
- 录制脚本通常依赖固定的屏幕坐标,如果窗口移动或缩放,回放会失败。图像查找 可以部分解决这个问题。
如果只是想录制一次鼠标点击(比如挂机),建议直接用 TinyTask(无需安装,快捷方便),如果需要写更加细粒度的控制,Python 方案是最佳选择。