
AutoPy 是一个轻量级跨平台的 Python 自动化工具,能模拟鼠标键盘操作、屏幕取色及简单图像交互,帮助高效完成重复性任务。相比 PyAutoGUI,它更小巧流畅,适合基础自动化需求。
平台 | 一键命令 |
|---|---|
Linux | sudo apt install libxtst6 libpng-dev && pip install -U autopy |
macOS | brew install libpng && pip install -U autopy |
Windows | pip install -U autopy(已含预编译 wheel) |
验证:
import autopy, time, threading, csv, os, winsound AutoPy 适用于多种自动化场景:
1、数据录入:自动填写表单或输入重复数据。
2、系统测试:自动化点击和键盘输入测试。
3、日常办公:自动回复消息或执行重复操作。
4、游戏辅助:执行简单的游戏操作。
5、屏幕监控:检测特定区域的颜色变化。
import autopy
import timedef click_position(x, y):
"""移动到指定位置并点击"""
autopy.mouse.move(x, y)
time.sleep(0.5) # 等待移动完成
autopy.mouse.click()
# 点击屏幕坐标(500, 300)的位置
click_position(500, 300)import autopydef
type_and_enter(text):
"""输入文本并回车"""
autopy.key.type_string(text)
autopy.key.tap(autopy.key.Code.RETURN)
# 输入"Hello, World!"并回车
type_and_enter("Hello, World!")import autopy
import timedef
wait_for_color(x, y, target_color, timeout=10):
"""等待屏幕某点颜色变为目标颜色"""
start_time = time.time()
while time.time() - start_time < timeout:
current_color = autopy.bitmap.capture_screen().get_color(x, y)
if current_color == target_color:
return True
time.sleep(0.5)
return False
# 等待(100,100)位置变为红色(0xFF0000)
if wait_for_color(100, 100, 0xFF0000):
print("检测到红色!")import autopy
import timedef
auto_login(username, password):
# 等待1秒确保窗口已打开
time.sleep(1)
# 定位到用户名输入框并输入
autopy.mouse.move(300, 200)
autopy.mouse.click()
autopy.key.type_string(username)
# 定位到密码输入框并输入
autopy.mouse.move(300, 250)
autopy.mouse.click()
autopy.key.type_string(password)
# 点击登录按钮
autopy.mouse.move(300, 300)
autopy.mouse.click()
# 使用示例
auto_login("your_username", "your_password")# 01_auto_login.py
importautopy, time
SCALE = autopy.screen.scale()
WIDTH, HEIGHT = autopy.screen.size()
def click(x, y):
autopy.mouse.move(x/SCALE, y/SCALE)
autopy.mouse.click()
def login(user, pwd):
time.sleep(0.8) # 留给窗口激活
click(300*WIDTH/1920, 200*HEIGHT/1080)
# 用户名框
autopy.key.type_string(user)
click(300*WIDTH/1920, 250*HEIGHT/1080)
# 密码框
autopy.key.type_string(pwd)
click(300*WIDTH/1920, 300*HEIGHT/1080) # 登录按钮
if__name__ == "__main__":
login("your_username", "your_password")# 02_csv_filler.py
importcsv, autopy, time
deffill_row(row: dict):
"""按列名顺序填表 → Tab 跳转"""
for v in row.values():
autopy.key.type_string(str(v))
time.sleep(0.1)
autopy.key.tap(autopy.key.Code.TAB)
with open("data.csv", newline='', encoding='utf-8-sig') as f:
for line in csv.DictReader(f):
fill_row(line)
autopy.key.tap(autopy.key.Code.RETURN) # 提交
time.sleep(0.5) # 等待页面刷新# 03_color_watch.py
importautopy, threading, time, winsound
TARGET_COLOR = 0xFF0000 # 纯红
X, Y = 100, 100
ALARM_SEC = 1
defwatch():
whileTrue:
screen = autopy.bitmap.capture_screen()
if screen.get_color(X, Y) == TARGET_COLOR:
winsound.Beep(2000, 500)
time.sleep(ALARM_SEC)
time.sleep(0.5)
threading.Thread(target=watch, daemon=True).start()
print("后台监控中,按 Ctrl+C 退出")
input()# 04_game_helper.py
import autopy, time, keyboard # pip install keyboard
INTERVAL = 0.05 # 20 次/秒
running = False
deftoggle():
globalrunning
running = notrunning
print("连点"ifrunningelse"停止")
keyboard.add_hotkey("F6", toggle)
print("按 F6 开始/停止连点,F7 退出")
whileTrue:
ifrunning:
autopy.mouse.click()
time.sleep(INTERVAL)
ifkeyboard.is_pressed("F7"):
break# 05_button_test.py
import autopy, time, random
def random_click_in_rect(x1, y1, x2, y2):
x = random.randint(x1, x2)
y = random.randint(y1, y2)
autopy.mouse.move(x, y)
autopy.mouse.click()
# 假设按钮区域 400×300 起始 (100,100)
for i in range(100):
random_click_in_rect(100, 100, 500, 400)
time.sleep(0.2)AutoPy 内置归一化互相关,速度快:
# 06_template_match.py
importautopy, time, os
TEMPLATE = autopy.bitmap.Bitmap.open("button.png")
def find_and_click(threshold=0.9):
screen = autopy.bitmap.capture_screen()
pos = screen.find_bitmap(TEMPLATE, threshold)
ifpos:
autopy.mouse.move(pos[0] +TEMPLATE.width//2,
pos[1] +TEMPLATE.height//2)
autopy.mouse.click()
return True
return False
# 轮询 30 秒
for _ in range(60):
if find_and_click():
print("找到并点击")
break
time.sleep(0.5)
else:
print("超时未找到")# 07_screenshot_report.py
import autopy, datetime, os
SAVE_DIR = "screenshots"os.makedirs(SAVE_DIR, exist_ok=True)
def shot():
bmp = autopy.bitmap.capture_screen()
file_name = f"{SAVE_DIR}/shot_{datetime.datetime.now():%Y%m%d_%H%M%S}.png"
bmp.save(file_name)
print("保存 →", file_name)
# 每 30 分钟截一次
whileTrue:
shot()
time.sleep(30*60)现象 | 原因 | 快速修复 |
|---|---|---|
ImportError: libpng16.so.16 | 系统缺少 libpng | sudo apt install libpng16-16 |
坐标偏差 | 未考虑屏幕缩放 | 使用 autopy.screen.scale() 动态换算 |
找不到图 | 阈值过高/模板尺寸不对 | 调低 threshold 或重截模板 |
点击无效 | 窗口未激活 | 先 alt+tab 或 win32gui 置顶窗口 |
1、AutoPy 适合简单的自动化任务,对于复杂的图像识别需求可能需要结合其他库
2、使用前请确保目标窗口已打开并处于活动状态
3、不同屏幕分辨率可能需要调整坐标
4、自动化操作可能被某些应用程序检测并阻止
AutoPy 作为轻量级自动化工具,能够帮助从重复性工作中解放出来,提高工作效率。对于更复杂的需求,可以考虑结合 PyAutoGUI 或其他自动化工具使用。
“无他,惟手熟尔”!有需要就用起来。
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!