一个真实需求:让 AI 帮我操作公司内网系统。过程中 AppleScript 全线失败、System Events 权限违例、键盘输入中文乱码。最后靠 Accessibility API 全部打通,全程只用「辅助功能」一个权限,零第三方依赖。
我每天要在公司内网系统里做一堆固定动作:登录、展开菜单、选季度、点查询、导出、下载附件。这些动作没有 API,只能用手点。
用 WorkBuddy 做其他事情都很顺——写文档、分析表格、跑脚本。唯独到了"点鼠标"这一步卡住,因为它跑在沙箱里,默认没有桌面控制权。
于是我开始折腾。这篇文章记录的就是这条路的完整过程,包括四次失败和最后见效的方案,代码可以直接抄走。
macOS 上让程序控制别的程序,最经典的路子就是 AppleScript。我先试了最标准的三句:
# 读当前页面标题
osascript -e 'tell application "Safari" to get name of front document'
# 读当前页面 URL
osascript -e 'tell application "Safari" to get URL of front document'
# 执行页面里的 JS
osascript -e 'tell application "Safari" to do JavaScript "document.title" in front document'三条全部返回同一个错:
execution error: Safari got an error: 权限违例 (-10004)-10004 是 errAEEventNotPermitted,意思是"你不被允许发送 Apple Event"。
我去系统设置里把「自动化」面板里 WorkBuddy 下面的 Safari、访达、System Events 全部勾上,确认三个开关都是蓝色的,再测——还是 -10004。
这里有个很关键的细节,官方文档里不太显眼:
Apple Events 权限(TCC 的 kTCCServiceAppleEvents)是在进程启动时读取并缓存的。
系统记住的是"这个进程启动时没有这个权限"。所以对已经在运行的那个进程,你在设置里勾开关不会立刻生效。必须 Cmd+Q 完全退出、重新启动,新进程才能拿到授权。
我照做了,重启后再测——依然是 -10004。
到这一步我才意识到,问题可能不在"有没有勾",而在"授权对象是谁"。TCC 授权的粒度是发起调用的那个二进制。如果会话实际跑在某个宿主 App 里,你勾错了对象,开关是蓝的,但被授权的不是真正干活的进程。
教训 1:遇到
-10004,先别急着反复勾开关。先确认"到底哪个进程在发 Apple Event",再对着那个进程授权。
既然读不到 DOM,我退一步:截图当眼睛、坐标当手,总行吧。
截图倒是通了(screencapture -x 正常出图)。但模拟鼠标和键盘需要另一套 API。为了不引入第三方依赖,我用 ctypes 直接调 CoreGraphics:
import ctypes
cg = ctypes.cdll.LoadLibrary(
"/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics")
class CGPoint(ctypes.Structure):
_fields_ = [("x", ctypes.c_double), ("y", ctypes.c_double)]
cg.CGEventCreateMouseEvent.restype = ctypes.c_void_p
cg.CGEventCreateMouseEvent.argtypes = [
ctypes.c_void_p, ctypes.c_uint32, CGPoint, ctypes.c_uint32]
cg.CGEventPost.argtypes = [ctypes.c_uint32, ctypes.c_void_p]鼠标点击很好用,一次就通。但输入中文时出事了——我在网页搜索框里想输入「周板报」,框里出现的是:
鈀鵒諦三个乱码字。这是典型的编码单元搞错:CGEventKeyboardSetUnicodeString 的第二个参数是 UTF-16 单元个数,不是字节数。我按 UTF-8 字节传,长度和内容全错位。
改对之后是这样:
def type_text(text):
units = text.encode("utf-16-le")
n = len(units) // 2 # ← UTF-16 单元数,不是字节数
buf = ctypes.create_string_buffer(units, len(units))
for down in (True, False):
ev = cg.CGEventCreateKeyboardEvent(None, 0, down)
cg.CGEventKeyboardSetUnicodeString(ev, n, buf)
cg.CGEventPost(0, ev)
time.sleep(0.015)但说实话,修好之后依然不稳:输入法状态、焦点位置、按键时序都会影响结果,十次里有两三次丢字或错位。
教训 2:模拟键盘输入中文,是所有方案里最脆的一环。能用别的办法就别用它。
失败到第三次,我盯上了一个细节:
ax.AXIsProcessTrusted() # → False这个函数查的是「辅助功能」权限。当我把它对应的开关打开后,立刻返回 True,不需要重启。
这就是关键差异:
权限 | 授予后是否立即生效 | 背后机制 |
|---|---|---|
Apple Events(自动化) | ❌ 需重启进程 | TCC 在进程启动时快照 |
辅助功能(Accessibility) | ✅ 立即生效 | 每次调用实时查询 |
顺着这条线往下想:既然辅助功能是实时查询的,那它背后那套 Accessibility API 应该也是可用的——而它恰好能读写任意 App 的 UI 元素树。
这比读 DOM 更底层,也更强:不依赖浏览器调试接口,不依赖 Apple Events,只依赖一个权限。
结果一试就通。
同样四个函数,全在 ApplicationServices 里,ctypes 直接调,零依赖:
ax = ctypes.cdll.LoadLibrary(
"/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices")
ax.AXUIElementCreateApplication.restype = ctypes.c_void_p
ax.AXUIElementCreateApplication.argtypes = [ctypes.c_int]
ax.AXUIElementCopyAttributeValue.restype = ctypes.c_int
ax.AXUIElementCopyAttributeValue.argtypes = [
ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)]
ax.AXUIElementPerformAction.restype = ctypes.c_int
ax.AXUIElementPerformAction.argtypes = [ctypes.c_void_p, ctypes.c_void_p]拿到某个 App 的根元素后,递归 AXChildren 一路往下走,就能把界面上所有元素打出来:
def walk(el, depth=0):
if not el or depth > 40:
return
role = to_str(attr(el, "AXRole"))
title = to_str(el, "AXTitle") or to_str(el, "AXValue") or ""
print(" " * depth + f"[{role}] {title}")
for child in children(el):
walk(child, depth + 1)实际输出长这样(一个网页系统):
[AXWindow] U视界 - 首页
[AXGroup]
[AXStaticText] 联合利华应付对账单
[AXStaticText] 联合利华应收对账单
[AXStaticText] 票扣
[AXGroup]
[AXTextField] https://example.internal/sfep/home
[AXButton] SSO登录
[AXButton] 企业微信登录页面上的按钮、输入框、文字,全部可读。比起 OCR 截图,这是降维打击:不挑分辨率、不怕窗口被挡、不受缩放影响。
有了文字,就可以按语义定位,不用算坐标:
def click_by_text(root, text):
for el in find_all(root, text):
if ax.AXUIElementPerformAction(el, cfstr("AXPress")) == 0:
return True
return False到这里,"打开系统 → 点菜单 → 选条件 → 点查询 → 读表格"整条链路就能全自动跑了。
我第一次按文字定位菜单项,拿到了元素,AXPress 却失败。打印它的可用动作才发现:
[AXGroup] 应付对账单 actions=(AXShowMenu)容器 AXGroup 没有 AXPress。真正的可点元素是它里面的 AXStaticText:
[AXStaticText] 应付对账单 actions=(AXPress)所以查找时要继续往下钻,找到带 AXPress 的那一层。写个诊断命令打印 AXRole + 动作列表,一眼就看清:
actions = ax.AXUIElementCopyActionNames(el, ctypes.byref(names))这条最省时间:卡住时先查 actions,别猜。
内网系统是二级菜单结构。点「应付对账单」不会跳页,只会展开 4 个子项。而且——
已经展开时再点一次,会把它折叠。
我的循环遍历脚本因此一半失败:上一轮的展开状态带到了下一轮,点击直接折叠,子项消失,然后按旧坐标点到了别的东西。
修法是每次点击前先判断状态,或者干脆每次只处理一个、处理完重新从根节点找。
这个坑最阴。元素明明找到了,点下去毫无反应。打印坐标才发现:
应付对账单 @(-412,256 88x40)x = -412,说明窗口左边缘跑到屏幕外面去了。原因是窗口宽度 1324px,而屏幕逻辑宽度只有 1280px。
不是拖一下能解决的——拖的时候窗口会自己回弹。正确做法是直接用 AX 改窗口属性:
# 先设尺寸,再设位置,顺序反了会被系统夹回去
ax.AXUIElementSetAttributeValue(win, cfstr("AXSize"), axvalue_size(1260, 770))
ax.AXUIElementSetAttributeValue(win, cfstr("AXPosition"), axvalue_point(10, 34))设完坐标立刻转正。
顺带一个经验:任何"点不到"的问题,第一步都去打印元素坐标。负坐标、零尺寸、坐标在屏幕外,比任何逻辑 bug 都常见。
AXTextField 支持直接赋值:
ax.AXUIElementSetAttributeValue(field, cfstr("AXValue"), cfstr("周板报"))返回值 0 就是成功,读回来验证即可。不经过键盘、不经过输入法、不怕编码。
这条路比模拟键盘可靠一个数量级。同样的思路可以用在粘贴板:
printf '要输入的文本' | pbcopy # 然后模拟一次 Cmd+V这一点必须说清楚,不然容易白折腾。
能用:把 UI 结构暴露给系统的 App——Safari、Chrome、Finder、原生 Cocoa 应用、大部分 Web 系统(因为浏览器会传递 AX 树)。
不能用:自绘界面的 App。典型的是 Qt / CEF 画的客户端。我拿微信试过,AXChildren 展开后只有一个窗口和三个没有标题的按钮:
[AXWindow] 微信
[AXButton]
[AXButton]
[AXButton]聊天列表、消息气泡、按钮文字,一个都读不到。因为它整块是画布,不是原生控件。
这类 App 只能退回"截图 + 坐标点击":看一眼、点一下、再看一眼。能用,但慢,而且窗口一挪就失效。
判断方法:拿 AX 树 dump 一次,如果深度超过 3 层还没出现任何
AXStaticText,基本就是自绘的,别浪费时间。
把上面这些拼起来,一个能跑的骨架大约 60 行:
#!/usr/bin/env python3
"""按文字操作任意 Mac App 的界面元素。只依赖「辅助功能」权限。"""
import ctypes, ctypes.util, subprocess
cf = ctypes.cdll.LoadLibrary(
"/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
ax = ctypes.cdll.LoadLibrary(
"/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices")
UTF8 = 0x08000100
cf.CFStringCreateWithCString.restype = ctypes.c_void_p
cf.CFStringCreateWithCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32]
cf.CFStringGetCString.restype = ctypes.c_bool
cf.CFStringGetCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_long, ctypes.c_uint32]
cf.CFGetTypeID.restype = ctypes.c_ulong
cf.CFGetTypeID.argtypes = [ctypes.c_void_p]
cf.CFStringGetTypeID.restype = ctypes.c_ulong
cf.CFArrayGetTypeID.restype = ctypes.c_ulong
cf.CFArrayGetCount.restype = ctypes.c_long
cf.CFArrayGetCount.argtypes = [ctypes.c_void_p]
cf.CFArrayGetValueAtIndex.restype = ctypes.c_void_p
cf.CFArrayGetValueAtIndex.argtypes = [ctypes.c_void_p, ctypes.c_long]
ax.AXUIElementCreateApplication.restype = ctypes.c_void_p
ax.AXUIElementCreateApplication.argtypes = [ctypes.c_int]
ax.AXUIElementCopyAttributeValue.restype = ctypes.c_int
ax.AXUIElementCopyAttributeValue.argtypes = [
ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)]
ax.AXUIElementPerformAction.restype = ctypes.c_int
ax.AXUIElementPerformAction.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
ax.AXIsProcessTrusted.restype = ctypes.c_bool
_k, STR = [], cf.CFStringGetTypeID()
def cfstr(s):
r = cf.CFStringCreateWithCString(None, s.encode(), UTF8)
_k.append(r); return r
def to_str(ref):
if not ref or cf.CFGetTypeID(ref) != STR: return None
n = cf.CFStringGetLength(ref) * 4 + 8
buf = ctypes.create_string_buffer(n)
return buf.value.decode() if cf.CFStringGetCString(ref, buf, n, UTF8) else None
def attr(el, name):
out = ctypes.c_void_p()
if ax.AXUIElementCopyAttributeValue(el, cfstr(name), ctypes.byref(out)) != 0:
return None
_k.append(out); return out
def children(el):
arr = attr(el, "AXChildren")
if not arr or cf.CFGetTypeID(arr) != cf.CFArrayGetTypeID(): return []
return [cf.CFArrayGetValueAtIndex(arr, i) for i in range(cf.CFArrayGetCount(arr))]
def pid_of(app):
return int(subprocess.check_output(["pgrep", "-x", app]).split()[0])
def find(el, needle, out, d=0):
if not el or d > 60: return
texts = [t for t in (to_str(attr(el, "AXValue")), to_str(attr(el, "AXTitle"))) if t]
if any(needle in t for t in texts): out.append(el)
for c in children(el): find(c, needle, out, d + 1)
if __name__ == "__main__":
if not ax.AXIsProcessTrusted():
raise SystemExit("缺辅助功能权限:系统设置 → 隐私与安全性 → 辅助功能")
root = ax.AXUIElementCreateApplication(pid_of("Safari"))
hits = []
find(root, "登录", hits)
for el in hits:
for name, val in (("AXTitle", None), ("AXRole", None)):
pass
if ax.AXUIElementPerformAction(el, cfstr("AXPress")) == 0:
print("已点击")
break配合 shell 侧的一条命令,就是完整的"打开 → 点击":
open -a Safari "https://example.com"
sleep 4
python3 ax.py click Safari "登录"用了几天,说几个必须承认的局限:
但反过来,它的价值也很明确:那些没有 API、又必须人点的老系统,从此可以自动化了。 而且因为走的是系统级无障碍通道,不注入脚本、不 hook 进程,行为上跟真实的辅助功能工具一致。
回头看,四次失败里有三次不是因为"技术不行",而是因为试错了方向:
真正让事情通的是换了个权限模型去看问题:同样是"让程序控制程序",Apple Events 和 Accessibility 是两套完全独立的机制,前者被堵死不代表后者不可用。
如果你也在 Mac 上折腾桌面自动化,我的建议是:先花两分钟确认 AXIsProcessTrusted() 是不是 True,然后直接走 Accessibility API。 别在 AppleScript 上耗太久,那条路在 TCC 收紧之后只会越来越窄。
代码已去掉业务相关部分,ax.py 本身是通用的,稍作修改就能用在别的系统上。
本文基于 macOS 上的真实操作过程整理,所有命令与报错均为实际回显。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。