使用AppleScript在Safari中选择文件
问题描述:
我正在尝试编写一些自动化代码(主要是在Ruby Selenium中)。在某些时候,在Safari中打开文件选择器,以便用户可以选择要上传的文件。硒不能处理这个问题,但我认为AppleScript应该可以。我是AppleScript的新手,无法找到自动执行文件选择器对话框的人的任何样板代码。我正在阅读AppleScript文档,但任何想法都会对您有所帮助。使用AppleScript在Safari中选择文件
答
一些更多的搜索,我发现这里有很大答案:Applescript file dialog with UI scripting
这里是我最终使用:
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
运行结束
答
我刚刚发现的另一个选项是指定的目录使用命令行:
do shell script "defaults write com.apple.Safari NSNavLastRootDirectory /path/to/directory"
这样你c在UI脚本中做得稍微少一些。在打开文件选择器之前运行此命令,它会将您置于指定的目录中。在这个目录中包含你需要的所有文件,你可以编写命令+ a来选择它们,然后返回。
您是否试图以编程方式告诉Safari在文件选择器打开后上传特定文件,或让Safari首先打开选择器?前者为 – Asmus 2011-03-02 16:27:43
。 Selenium点击一个打开Safari文件选择器的链接,然后用文件位置调用我的AppleScript,而且我们很好。至少我希望如此 - 即将尝试。 ;) – 2011-03-02 18:42:08