如何使用 AppleScript 单击此网页按钮

How to click on this webpage button with AppleScript

我无法单击特定网站上的 "search" 按钮。该网站是一项订阅服务,因此我附上了在 "inspect" 模式下拉出的页面图片以及我的代码。

我的代码:

set myURL to "https://www.uptodate.com/contents/search"

tell application "Safari"
    activate
    make new document with properties {URL:myURL}
end tell

tell application "System Events"
    repeat until exists (UI elements of groups of toolbar 1 of window 1 of application process "Safari" whose name = "Reload this page")
        delay 0.3
    end repeat
end tell

inputByID("tbSearch", "myVar")

clickClassName("newsearch-submit", 0)



###InputByID###
to inputByID(theId, theValue)
    tell application "Safari"
        do JavaScript "document.getElementById('" & theId & "').value ='" & theValue & "';" in document 1
    end tell
end inputByID

###ClickByClass###
to clickClassName(theClassName, elementnum)
    tell application "Safari"
        do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
    end tell
end clickClassName

作为替代方案,您可以使用 UI 脚本,其中 系统事件 执行一些 击键.

以下示例 AppleScript codemacOS 中对我有用高塞拉1:

set myURL to "https://www.uptodate.com/contents/search"

tell application "Safari"
    activate
    make new document with properties {URL:myURL}
end tell

tell application "System Events"
    repeat until (accessibility description of ¬
        button 1 of UI element 1 of every group of toolbar 1 of window 1 of ¬
        process "Safari" whose name = "Reload this page") contains "Reload this page"
        delay 0.5
    end repeat
end tell

tell application "Safari"
    do JavaScript "document.getElementById('tbSearch').value ='PPE';" in document 1
end tell

tell application "System Events"
    keystroke space
    key code 51 -- # Press the delete key to remove the space.
    keystroke return
end tell
  • 1 注意: 对于 macOS Mojave 及更高版本,更改 UI element 1在上面的 repeat loopUI element 2



注意:示例 AppleScript code 就是这样,不包含任何可能适当的错误处理。用户有责任根据需要添加任何 错误处理 。查看 try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. Additionally, the use of the delay 命令 在适当的事件之间可能是必要的,例如delay 0.5,适当设置延迟

我玩过这个,当然没有订阅不能真正测试它,但也许你可以看看这是否适合你 - 它似乎有效:

tell application "Safari"
    --activate --can work with or w/o Safari in foreground
    set myURL to "https://www.uptodate.com/contents/search"
    make new document with properties {URL:myURL}
    delay 5 -- just waits for (hopefully) the page to load
    set d to do JavaScript "document.forms[0][0].value = 'joint pain'" in document 1
    do JavaScript "document.forms['searchForm'].submit();" in document 1

end tell