使用AppleScript在Safari中选择文件

Ben*_*ynn 5 safari macos applescript

我正在尝试编写一些自动化代码(主要在Ruby Selenium中).在某些时候,在Safari中打开文件选择器,以便用户可以选择要上载的文件.Selenium无法处理这个,但我认为AppleScript应该能够.我是AppleScript的新手,并且无法找到任何自动执行文件选择器对话框的样板代码.我正在阅读AppleScript文档,但任何想法都会有所帮助.

Ben*_*ynn 4

经过更多搜索,我在这里找到了一个很好的答案:Applescript filedialog 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
Run Code Online (Sandbox Code Playgroud)

结束运行