PyAutoGUI自动化操作指南
1️⃣ 准备工作
# 安装库(在命令提示符执行)
pip install pyautogui
2️⃣ 核心功能速查表
| 功能 | 代码示例 | 说明 |
|---|---|---|
| 鼠标移动 | pyautogui.moveTo(100,200) | 移动到屏幕坐标(100,200) |
| 鼠标点击 | pyautogui.click() | 当前位置左键单击 |
| 键盘输入 | pyautogui.write('hello') | 输入文本 |
| 按键操作 | pyautogui.press('enter') | 按回车键 |
| 屏幕截图 | pyautogui.screenshot() | 截取当前屏幕 |
| 图像定位 | pyautogui.locateOnScreen('button.png') | 查找图片位置 |
3️⃣ 抢红包实战示例(以微信为例)
import pyautogui
import time
# 步骤1:打开微信
pyautogui.hotkey('win', 'r') # 打开运行窗口
pyautogui.write('wechat') # 输入微信
pyautogui.press('enter') # 回车打开
time.sleep(3) # 等待3秒加载
# 步骤2:定位红包
red_packet = None
while not red_packet:
# 在屏幕上查找红包图标(需提前截图保存为red.png)
red_packet = pyautogui.locateOnScreen('red.png', confidence=0.8)
time.sleep(0.5) # 每0.5秒检测一次
# 步骤3:点击红包
x, y = pyautogui.center(red_packet) # 获取红包中心坐标
pyautogui.click(x, y) # 点击红包
time.sleep(1) # 等待加载
# 步骤4:打开红包
open_btn = pyautogui.locateOnScreen('open.png') # 查找"开"按钮
if open_btn:
x, y = pyautogui.center(open_btn)
pyautogui.click(x, y)
print("成功抢到红包!")
else:
print("手慢了...")
4️⃣ 通用抢购模板(需配合安卓模拟器下载抢票、购物APP使用)
import pyautogui
import time
# 设置安全边界(防止失控)
pyautogui.FAILSAFE = True # 鼠标移到左上角可中断程序
target_time = "2023-12-31 20:00:00" # 设置开抢时间
while True:
now = time.strftime("%Y-%m-%d %H:%M:%S")
if now >= target_time:
# 执行抢购操作
pyautogui.click(800, 500) # 点击购买按钮位置
pyautogui.press('enter') # 确认购买
print("执行成功!")
break
time.sleep(0.1) # 每0.1秒检查时间
5️⃣ 注意事项
-
提前准备:
- 截图保存目标按钮(如"购买""立即抢")
- 测试坐标位置:运行
pyautogui.position()查看鼠标坐标
-
调优技巧:
# 调整识别精度(0-1之间) pyautogui.locateOnScreen('button.png', confidence=0.7) # 添加随机延迟(避免被检测) import random time.sleep(0.5 + random.random()) # 随机延迟0.5-1.5秒 -
道德提醒:
请遵守平台规则,本教程仅用于学习自动化技术原理,勿用于破坏公平性的行为
6️⃣ 错误排查
try:
pyautogui.click(1000, 600)
except Exception as e:
print(f"错误: {e}")
# 保存错误截图
pyautogui.screenshot('error.png')
建议:先在记事本等安全环境练习,熟练掌握后再实战操作!
2万+

被折叠的 条评论
为什么被折叠?



