本文目录导读:

我来介绍几种编写键鼠自动化脚本的方法,按推荐程度排序:
Python + PyAutoGUI(最推荐)
安装
pip install pyautogui
基本示例
import pyautogui
import time
# 获取屏幕尺寸
screen_width, screen_height = pyautogui.size()
# 移动鼠标并点击
pyautogui.moveTo(100, 200, duration=1) # 移动到(100,200)
pyautogui.click() # 左键点击
# 键盘操作
pyautogui.write('Hello World', interval=0.1) # 输入文字
pyautogui.press('enter') # 按回车
# 组合键
pyautogui.hotkey('ctrl', 'c') # 复制
pyautogui.hotkey('ctrl', 'v') # 粘贴
# 拖动
pyautogui.drag(300, 0, duration=0.5) # 向右拖动
# 截图并找图
loc = pyautogui.locateOnScreen('button.png')
if loc:
pyautogui.click(loc)
AutoHotkey(Windows专用)
基本语法
; 热键定义
^j:: ; Ctrl+J
Send, Hello World{Enter}
MouseMove, 500, 300
Click
return
; 鼠标宏
XButton1:: ; 鼠标侧键
Send ^c ; 复制
Sleep 100
Send ^v ; 粘贴
return
; 延迟运行
SetTimer, MyAction, 5000 ; 5秒后执行
MyAction:
Send {F5} ; 刷新
return
JavaScript + Puppeteer(网页自动化)
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// 模拟点击
await page.click('#button-id');
// 输入文本
await page.type('#input-id', 'Hello World');
// 键盘操作
await page.keyboard.press('Enter');
await browser.close();
})();
按键精灵(适合新手)
简单示例脚本:
// 循环点击
For i = 1 To 10
MoveTo 500, 300
LeftClick 1
Delay 1000
Next
// 键盘操作
KeyPress "Enter", 1
SayString "Hello World"
实用技巧
安全措施
import pyautogui # 启用紧急停止(快速将鼠标移到左上角) pyautogui.FAILSAFE = True # 添加延迟避免过快操作 pyautogui.PAUSE = 0.1
坐标定位
# 获取鼠标当前位置
import pyautogui
while True:
x, y = pyautogui.position()
print(f"鼠标位置: ({x}, {y})", end='\r')
图像识别
# 找到并点击特定图像
def find_and_click(image_path, confidence=0.9):
location = pyautogui.locateOnScreen(image_path, confidence=confidence)
if location:
center = pyautogui.center(location)
pyautogui.click(center)
return True
return False
选择建议
- 简单任务:按键精灵或AutoHotkey
- 跨平台:Python + PyAutoGUI
- 网页自动化:Puppeteer/Selenium
- 游戏脚本:AutoHotkey(注意游戏规则)
注意事项
- 不要用于违规用途(如游戏外挂)
- 添加适当延迟避免系统过载
- 保留紧急停止机制
- 测试时用录屏软件记录过程
需要我详细讲解某个具体场景的自动化实现吗?