使用AppleScript实现Safari自动化抓取网页通知的问题咨询
AppleScript 实现网页通知转系统推送解决方案
前置配置
- 先开启Safari的JavaScript权限:打开Safari偏好设置→「高级」选项卡→勾选「在菜单栏中显示开发菜单」,再进入开发菜单勾选「允许Apple事件中的JavaScript」,否则
do JavaScript指令会直接报错。
核心功能实现代码
1. 定位指定Safari页面
不需要将页面置于前台,通过页面标题即可精准匹配标签页:
set targetPageTitle to "你要监控的网页的完整标题" tell application "Safari" -- 适配多窗口场景,找不到对应页面会抛出可捕获的错误 set targetTab to first tab of every window whose name is equal to targetPageTitle end tell
2. 容错式DOM元素提取
针对元素不存在时的报错问题,直接在JS层做兼容,同时用AppleScript的try块做双层兜底,不会中断脚本运行:
set monitorClass to "你要抓取的DOM元素类名" set elementIndex to 0 -- 对应你定义的$num,同类元素第一个序号为0 set fetchResult to "" try tell application "Safari" -- 用JS可选链直接返回空字符串,避免元素不存在时报错 set fetchResult to do JavaScript "document.getElementsByClassName('" & monitorClass & "')[" & elementIndex & "]?.innerText || ''" in targetTab end tell on error set fetchResult to "" end try
3. HTML标签剥离工具方法
如果需要处理带标签的原始HTML内容,直接调用以下内置方法即可:
on stripHTML(rawHTML) set originalDelimiters to AppleScript's text item delimiters set AppleScript's text item delimiters to {"<", ">"} set splitContent to text items of rawHTML set plainText to "" repeat with i from 1 to count of splitContent if i mod 2 = 1 then set plainText to plainText & item i of splitContent end repeat set AppleScript's text item delimiters to originalDelimiters return plainText end stripHTML -- 调用示例 set notificationContent to stripHTML(fetchResult)
4. 循环监控+去重推送逻辑
避免空转占用资源,同时防止同一个通知重复推送:
set lastPushContent to "" set checkInterval to 5 -- 检查间隔,单位为秒,不建议低于2秒 repeat -- 上述元素提取、文本处理逻辑放此处 if fetchResult is not "" and fetchResult is not equal to lastPushContent then display notification notificationContent with title "网页实时通知" sound name "Glass" set lastPushContent to fetchResult end if delay checkInterval end repeat
实用技巧
- 脚本需要长期后台运行的话,在脚本编辑器中选择「文件→导出」,文件格式选「应用程序」,勾选「运行处理程序后保持打开」即可。
- 如果监控页面会自动刷新,把标签页匹配逻辑放到循环内部,避免页面刷新后标题变更无法定位。
- 同类通知有多个的话,可以在JS层遍历所有对应类名的元素,拼接所有内容后再返回。
内容的提问来源于stack exchange,提问作者Visual Art Board
相关产品推荐
相关产品推荐

