AppleScript调用Safari JS获取img元素无返回值问题求助
问题解决:AppleScript调用JavaScript获取img元素无返回值
核心问题在于:AppleScript的do JavaScript命令无法直接接收DOM元素对象这类复杂结构,必须将其转换为字符串、基础数组或普通对象这类可序列化的数据类型。浏览器控制台能正常输出DOM元素是因为控制台会自动处理对象的格式化展示,但AppleScript不支持这类对象的跨环境传递。
修改后的代码示例(提取所有img的src属性):
tell application "Safari" set theWindow to front window set theTab to current tab of theWindow set asImages to (do JavaScript "Array.from(document.getElementsByTagName('img')).map(img => img.src);" in theTab) end tell
如果需要获取更多元素属性(比如alt文本和src),可以调整JavaScript部分返回包含多属性的对象数组:
tell application "Safari" set theWindow to front window set theTab to current tab of theWindow set asImages to (do JavaScript "Array.from(document.getElementsByTagName('img')).map(img => ({src: img.src, alt: img.alt}));" in theTab) end tell
原理说明:
- 用
Array.from()将getElementsByTagName返回的HTMLCollection转为标准数组(替代[].slice.call()也可以,效果一致) - 通过
map()方法将每个DOM元素转换为包含所需属性的普通对象/字符串,确保AppleScript能正确解析返回值
内容的提问来源于stack exchange,提问作者Chris Norman
相关产品推荐
相关产品推荐

