如何使元素选择为 return null 而不是在 applescript 中抛出错误

how to make the element selection to return null instead of throw error in applescript

我正在调试旧版桌面自动化工具,它使用 AppleScript 在 MacOS 上进行 UI 控制。其中一个脚本一直失败 error "System Events got an error: Can’t get static text \"2\" of window \"UISoup – mac_utils.py\" of application process \"pycharm\"." number -1728 from static text "2" of window "UISoup – mac_utils.py" of application process "pycharm",这里是脚本

tell application "System Events" to tell process "PyCharm"
    set visible to true
    set uiElement to static text "2" of window "UISoup – mac_utils.py" of application process "pycharm" of application "System Events"
    set layer to 1
    if uiElement = null then
        set layer to 0
        set collectedElements to {UI elements of front window, layer}
    else
        set layer to layer + 1
        set collectedElements to {null, layer}
        if name of attributes of uiElement contains "AXChildren" then
            set collectedElements to {value of attribute "AXChildren" of uiElement, layer}
        end if
    end if
end tell

如果找不到元素,这行 set uiElement to static text "2" of window "UISoup – mac_utils.py" of application process "pycharm" of application "System Events" 似乎应该将 uiElement 设置为 null。但实际上它会抛出错误。如何让它 return null 而不是抛出错误来让它工作?谢谢。

在 AppleScript 中,null 相当于 缺失值 。 GUI脚本时,进程应该frontmost。您可以使用命令 exists 检查现有的 UI 个元素(您也可以使用 try 块)。

tell application "System Events" to tell process "PyCharm"
    set frontmost to true
    -- set visible to true
    set uiElementExists to exists static text "2" of window "UISoup – mac_utils.py"
    set layer to 1
    if not uiElementExists then
        set layer to 0
        set collectedElements to {UI elements of front window, layer}
    else
        set layer to layer + 1
        set collectedElements to {missing value, layer}
        set uiElement to static text "2" of window "UISoup – mac_utils.py"
        if name of attributes of uiElement contains "AXChildren" then
            set collectedElements to {value of attribute "AXChildren" of uiElement, layer}
        end if
    end if
end tell