从Chrome中选择网页的所有内容,然后使用AppleScript保存到文本文件

时间:2016-11-25 00:44:51

标签: google-chrome applescript automator

我创建了一个Automator工作流程,以循环浏览Google Chrome窗口的所有标签,并将每个标签页上的网页保存到文本文件中。

    on run {input, parameters}

    tell application "Google Chrome"
        set windowList to every window
        repeat with theWindow in windowList
            set tabList to every tab in theWindow
            repeat with theTab in tabList
                select all
                copy selection
                set theTitle to title of theTab
                set theScript to "echo" & (selection as text) & "> $HOME/Desktop/tmp" & quoted form of POSIX path of theTitle & "-clipboard-file.txt"
                display dialog theScript
                do shell script theScript
            end repeat
        end repeat
    end tell

    return input
end run

然而,这会生成空文本文件。 我怀疑"复制选择"不与系统粘贴板交互。有没有办法可以将文本复制到粘贴板或直接导出到文本文件?

2 个答案:

答案 0 :(得分:1)

[这已经 [编辑] 包含魔术unicode友好"强制"。请参阅" unicode-friendly"下的更新行。评论。该行使用着名的AppleEvent代码选项 - 反斜杠选项 - shift-backslash 字符]

看起来你只想要文本,好像它被复制到剪贴板一样,保存到每个文件中。 我会提醒你使用你刚开始使用的方法,只是因为可能会出现没有标题会让你留下一个实际命名为" .txt"的文件的情况,这是不可见的!所以我说使用计数变量以及你拥有的东西,以防万一(这在我的机器上工作并且对无标题页面有保护):

--first, I get the desktop as an old mac style path, using the Finder:
tell application "Finder" to set dt to desktop as string

tell application "Google Chrome"
    set windowList to every window
    set tabCount to 1
    repeat with theWindow in windowList
        set tabList to every tab in theWindow
        repeat with theTab in tabList
            set wHTMLText to execute theTab javascript "document.body.innerText;"
            set thetitle to title of theTab
            if thetitle is "" then set thetitle to ("untitled" & (tabCount as string))
            set filePath to (dt & "tmp:" & thetitle & ".txt")
            set myFile to open for access filePath with write permission
            --unicode-friendly:
            write wHTMLText to myFile as «class utf8»
            close access myFile
            set tabCount to tabCount + 1
        end repeat
    end repeat
end tell

[编辑:]哦,如果你想要HTML,请使用" document.body.innerHTML;"并使用" .html"扩展

答案 1 :(得分:0)

我采取了一些不同的方法。这个脚本有效,但我仍然无法弄清楚如何将这些项目粘贴为列表

tell application "Google Chrome"
    every window
    URL of every tab of item 1 of result
    set the clipboard to the result as text
end tell
do shell script "pbpaste > ~/Desktop/ClipboardFile.txt"