Using AppleScript to choose a file in Safari
我正在尝试编写一些自动化代码(主要是在Ruby Selenium中)。有时会在Safari中打开文件选择器,以便用户可以选择要上传的文件。 Selenium无法处理此问题,但我认为AppleScript应该能够处理。我是AppleScript的新手,还没有找到自动执行文件选择器对话框的人的任何样板代码。我正在阅读AppleScript文档,但是任何想法都会对您有所帮助。
进行了更多搜索,我在这里找到了一个很好的答案:带有UI脚本的Applescript文件对话框
这是我最终使用的内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | on run argv tell application"Safari" activate -- Usage check set argc to count argv if argc is not greater than 0 then return"Usage: SafariFileChooser file_name [window_name]" end if -- The file we will choose to open set file_name to item 1 of argv -- Flip to the named window, if specified if argc is equal to 2 then set window_name to item 2 of argv set flip_count to index of window window_name repeat (flip_count - 1) times activate tell application"System Events" to keystroke"`" using command down end repeat end if -- Interact with the dialog using System Events (thanks mcgrailm) tell front window activate tell application"System Events" keystroke"g" using {shift down, command down} keystroke file_name delay 1 keystroke return delay 1 keystroke return end tell end tell end tell return 0 |
结束运行
我刚发现的另一个选项是使用命令行指定目录:
1 | do shell script"defaults write com.apple.Safari NSNavLastRootDirectory /path/to/directory" |
通过这种方式,您可以在UI脚本中完成的工作稍少一些。打开文件选择器之前,请运行此命令,它将把您放入指定的目录。在此目录中包含所有需要的文件,您只需编写脚本命令a即可选择所有文件并返回。