AppleScript实现Safari打印转PDF失败求助:无法选择PDF菜单选项
解决Safari打印转PDF的AppleScript执行问题
常见问题原因及修复方案
- UI元素路径不匹配:不同macOS/Safari版本的打印对话框UI结构存在差异,原脚本依赖
splitter group 1定位PDF按钮的方式可能失效,可直接从打印面板(sheet)中定位PDF按钮,避免层级依赖。 - 菜单引用时机问题:菜单展开后需确保完全加载,绑定按钮对象后再引用菜单,比重复查找更可靠。
- 辅助功能权限缺失:需确保「系统设置>隐私与安全性>辅助功能」中已勾选
System Events,这是GUI脚本运行的必要权限。
修正后的脚本代码
tell application "Safari" to activate tell application "System Events" tell process "Safari" -- 触发打印菜单 click menu item "Print…" of menu "File" of menu bar 1 -- 等待打印面板弹出 repeat until exists sheet 1 of window 1 delay 0.5 end repeat -- 绑定打印面板对象,简化后续定位 set printSheet to sheet 1 of window 1 -- 定位并点击PDF按钮 set pdfButton to menu button "PDF" of printSheet click pdfButton -- 等待PDF菜单展开 repeat until exists menu 1 of pdfButton delay 0.5 end repeat -- 选择"Save as PDF"选项 click menu item "Save as PDF" of menu 1 of pdfButton end tell end tell
备选方案:使用键盘快捷键替代UI定位
如果UI定位仍不稳定,可尝试用键盘模拟操作,避免依赖元素路径:
tell application "Safari" to activate tell application "System Events" tell process "Safari" -- 按⌘P打开打印对话框 keystroke "p" using command down delay 1 -- 按⇧⌘P打开PDF菜单 keystroke "p" using {shift down, command down} delay 0.5 -- 按回车选择默认的"Save as PDF"(需确保该项是菜单第一个选项) keystroke return end tell end tell
内容的提问来源于stack exchange,提问作者blackberryoctopus
相关产品推荐
相关产品推荐

