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

Safari 如何使用AppleScript单击此网页按钮,safari,applescript,Safari,Applescript,我在点击特定网站上的“搜索”按钮时遇到问题。该网站是一个订阅服务,所以我附加了一个在“检查”模式下拉起的页面图片以及我的代码 我的代码: 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

我在点击特定网站上的“搜索”按钮时遇到问题。该网站是一个订阅服务,所以我附加了一个在“检查”模式下拉起的页面图片以及我的代码

我的代码:

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代码在macOS High Sierra1中适用于我:

将myURL设置为“https://www.uptodate.com/contents/search"
告诉应用程序“Safari”
激活
创建具有属性{URL:myURL}的新文档
结束语
告诉应用程序“系统事件”
重复上述步骤,直到(可访问性说明)
窗口1的每组工具栏1的UI元素1的按钮1
进程“Safari”,其name=“Reload this page”)包含“Reload this page”
延迟0.5
结束重复
结束语
告诉应用程序“Safari”
执行文档1中的JavaScript“document.getElementById('tbSearch').value='PPE';”
结束语
告诉应用程序“系统事件”
击键空间
键代码51——#按delete键删除空格。
击键返回
结束语
  • 1注意:对于macOS Mojave和更高版本,在上面的
    重复
    循环中将
    UI元素1
    更改为
    UI元素2



注意:示例AppleScript代码仅此而已,不包含任何适当的错误处理。用户有责任根据需要添加任何适当的错误处理。请查看中的语句和语句。另见。此外,在适当的情况下,在事件之间可能需要使用该命令,例如延迟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

如果我在macOS High Sierra下的脚本编辑器中复制并粘贴您的代码并运行它,我看到的第一件事就是
repeat
循环永远不会退出。用我自己的代码替换它,它将等待加载。但是,即使将“myVar”设置为
tbSearch
输入字段的值,也不会单击搜索按钮,因为输入字段正在检查
keyup
keydown
事件,而这不会仅仅因为您设置了值而发生。这对我来说不起作用,这就是
dojavascript”文档['searchForm'].submit()
它所做的一切就是刷新窗口,这是我在发布答案之前使用UI脚本和系统事件来处理它的第一件事。此外,使用
delay
命令来等待页面完成加载可能不准确,以及我为什么使用我所做的代码来等待页面完成加载,因为它的代码行动不起作用。