Сохранение страницы и нажатие на всплывающее окно сохранения в Chrome с помощью AppleScript - PullRequest
0 голосов
/ 13 ноября 2018

Я хочу загрузить текстовый файл, открытый на вкладке в Chrome с помощью AppleScript. Я хочу, чтобы в диалоговом окне «Сохранить как» Mac было указано расширение по умолчанию и имя файла.

tell application "Google Chrome" to tell active tab of window 1 to save as "r1.txt"

Я пробовал этот подход, и некоторые другие подходы, такие как

activate application "Google Chrome"
tell application "System Events"
    tell process "chrome"
        keystroke "s" using {command down}
        delay 1
        click button "Save" of sheet 1 of window 1
     end tell
end tell

до сих пор не могу нажать кнопку сохранения в модальном режиме.

Ответы [ 2 ]

0 голосов
/ 13 ноября 2018

Мой подход к этой проблеме состоял в том, чтобы попытаться избежать сценариев пользовательского интерфейса, если это возможно, что может быть проблематичным и ненадежным. Вместо этого я решил использовать команду оболочки curl, чтобы выполнить загрузку за нас, вместо того, чтобы пытаться манипулировать Chrome для ее выполнения.

Все, что нам нужно, это место, куда нужно сохранить файл, которое я установил в качестве местоположения, по умолчанию Google Chrome , а именно ~/Downloads.

property path : "~/Downloads" -- Where to download the file to

use Chrome : application "Google Chrome"
property sys : application "System Events"

property window : a reference to window 1 of Chrome
property tab : a reference to active tab of my window
property URL : a reference to URL of my tab

property text item delimiters : {space, "/"}

on run
    -- Stop the script if there's no URL to grab
    if not (my URL exists) then return false

    -- Path to where the file will be saved
    set HFSPath to the path of sys's item (my path)
    -- Dereferencing the URL
    set www to my URL as text
    -- Extract the filename portion of the URL
    set filename to the last text item of www

    -- The shell script to grab the contents of a URL
    set sh to the contents of {¬
        "cd", quoted form of the POSIX path of HFSPath, ";", ¬
        "curl --remote-name", ¬
        "--url", quoted form of www} as text


    ## 1. Download the file
    try
        using terms from scripting additions
            do shell script sh
        end using terms from
    on error E
        return E
    end try


    ## 2. Reveal the downloaded file in Finder
    tell application "Finder"
        tell the file named filename in the ¬
            folder named HFSPath to if ¬
            it exists then reveal it
        activate
    end tell
end run

Это более длинный скрипт, чем ваш нынешний, но в большинстве своем это объявления переменных (и свойств), после чего скрипт выполняет две простые вещи:

  1. Захватывает URL активной вкладки в Chrome и загружает содержимое этого URL в указанную папку, сохраняя то же имя файла и расширение, что и удаленный файл;

  2. После завершения загрузки файл обнаруживается в Finder .

0 голосов
/ 13 ноября 2018

Это работает для меня, используя последнюю версию Google Chrome и последнюю версию MacOS Mojave

activate application "Google Chrome"
tell application "System Events"
    repeat while not (exists of menu bar item "File" of menu bar 1 of application process "Chrome")
        delay 0.1
    end repeat
    click menu bar item "File" of menu bar 1 of application process "Chrome"
    repeat while not (exists of menu item 11 of menu 1 of menu bar item "File" of menu bar 1 of application process "Chrome")
        delay 0.1
    end repeat
    click menu item 11 of menu 1 of menu bar item "File" of menu bar 1 of application process "Chrome"
    repeat while not (exists of UI element "Save" of sheet 1 of window 1 of application process "Chrome")
        delay 0.1
    end repeat
    click UI element "Save" of sheet 1 of window 1 of application process "Chrome"
end tell
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...