【问题标题】:Save the source of an open webpage from Safari with AppleScript使用 AppleScript 从 Safari 保存打开网页的源代码
【发布时间】:2011-11-30 04:05:19
【问题描述】:

如何编写一个脚本,将 Safari 中打开的网页保存到某个路径?

(该代码稍后将用于更复杂的脚本,因此使用系统事件的笨拙解决方案将无法做到。)大量谷歌搜索以找到使用保存源功能的脚本让我非常不了解,所以一个答案这可能是互联网上的第一个。我在下面粘贴了一些可能有用的东西。

可能有用的东西

Safari 的 AppleScript 字典中的这两个条目看起来很有用:

documentn [另请参阅 Standard Suite]:代表窗口中活动选项卡的 Safari 文档。

属性:

  • source (text, r/o) :文档中当前加载的网页的 HTML 源代码。
  • text (text, r/o) : 当前加载到文档中的网页的文本。对文本的修改不会反映在网页上。
  • URL(文本):文档的当前 URL。

及以后:

savev :保存一个对象。

保存说明符:命令的对象

  • [as text] :保存数据的文件类型。
  • [in alias] : 保存对象的文件。

几乎可以满足我的需求的脚本

此脚本确实保存了一个 HTML 文档,但与使用 Safari 的“导出为页面源”功能手动保存的文件相比,输出看起来有问题:

tell application "Safari"
(* Get a reference to the document *)
set myDoc to document of front window

(* Get the source of the page *)
set mySrc to source of myDoc

(* Get a file name *)
set myName to "Message_" & "0001" & ".html" -- the # will be modified later

tell application "Finder"
    (* Get a path to the front window *)
    set myPath to (target of front window) as string

    (* Get a file path *)
    set filePath to myPath & myName

    (* Create a brand new file *)
    set openRef to open for access (myPath & myName) with write permission

    (* Save the document source *)
    write mySrc to openRef

    (* Close the file *)
    close access openRef
end tell

这是我到目前为止写的:

到目前为止我写的脚本

  1. 这是我的第一次尝试:

    tell application "Safari"
        set pageToSaveSafariWindowIn to "Q:Ø:"
        set pageToBeSaved to front window
        save document pageToBeSaved as source in alias pageToSaveSafariWindowIn
    end tell
    

    以下是生成的日志:

    tell application "Safari"
        get window 1
            --> window id 6017
        save document (window id 6017) as source in alias "Q:Ø:"
            --> error number -1700 from window id 6017 to integer
    

    错误“Safari 出现错误:无法将窗口 id 6017 转换为整数类型。”从窗口 id 6017 到整数的数字 -1700

  2. 又一次尝试:

    tell application "Safari"
        save source of document in "Q:Ø:"
    end tell
    

    给出结果日志:

    错误“无法获取文档来源。”编号 -1728 来自文档的 «class conT»

【问题讨论】:

  • 我知道您想获得完整的页面,而不仅仅是普通的 html ?
  • 是的。最后,我选择了 GUI/系统事件解决方案。我打算在脚本更完善时发布它。

标签: macos safari applescript


【解决方案1】:

如果您要手动执行此任务,您将在 Safari 中查看源代码,将源代码复制到剪贴板,进入 HTML 源代码编辑器并创建一个新文档,将源代码粘贴进去,选择保存并导航到Documents 文件夹,命名文档,然后保存。

因此,当您想编写 AppleScript 来执行此任务时,关键是您仍想使用相同的应用程序,但不是手动运行它们,而是使用 AppleScript 运行它们。一个很棒的 AppleScriptable HTML 源代码编辑器是 TextWrangler,它可以从 Mac App Store 免费获得。

一旦你有一个 Web 浏览器 (Safari) 来从网络上获取 HTML 源代码和一个 HTML 源代码编辑器 (TextWrangler) 来创建和保存 HTML 文档,你就可以编写一个非常小的、非常容易编写的,很容易阅读,很容易维护这样的AppleScript:

tell application "Safari"
    activate
    if document 1 exists then
        set theDocumentTitle to the name of document 1
        set theDocumentSource to the source of document 1
        tell application "TextWrangler"
            activate
            set theNewDocument to make new document with properties {name:theDocumentTitle, text:theDocumentSource}
            set theDocumentsFolderPath to the path to the documents folder as text
            set theSaveFilePath to theDocumentsFolderPath & theDocumentTitle & ".html"
            save theNewDocument to file theSaveFilePath
        end tell
    end if
end tell

... 它将简单地要求 Safari 提供其最前面文档的名称和源代码,然后要求 TextWrangler 使用该信息在您的 Documents 文件夹中创建和保存匹配的 HTML 文档。这些是这两个应用程序都非常擅长的任务。你不必问两次或做很多解释。

【讨论】:

    【解决方案2】:
    set hyperlink to "http://www.google.com/"
    
    set sourceCode to (do shell script "curl " & hyperlink)
    
    do shell script "echo " & quoted form of sourceCode & " >> /Users/name/Desktop/test.csv"
    

    您可以重复执行此操作,它会将每个列出的站点中的每个源代码附加到您创建的文档的末尾。即

    set hyperlink to "http://www.aRepetitivePageSite.com/2014?page="
    set your_count to 1
    repeat until your_count = 10
      set sourceCode to (do shell script "curl " & (hyperlink & your_count as string as text))
      do shell script "echo " & quoted form of sourceCode & " >> /Users/name/Desktop/test.csv"
      set your_count to your_count + 1
    end repeat
    

    【讨论】:

      【解决方案3】:

      我找到了我认为更好/更简单的解决方案:

      tell application "Safari"
      activate
      set URL of document 1 to "http://www.apple.com"
      delay 5
      set myString to source of document 1
      end tell
      set newFile to POSIX file "/Users/myUsername/test.html"
      open for access newFile with write permission
      write myString to newFile
      close access newFile
      

      注意事项:

      • “文档 1 的来源”似乎仅在网页完全加载后才填充了正确的源文本。因此需要延迟。也许您可以使用较低的延迟。

      • 有一些解决方案推荐使用 curl。我没有尝试过,但我认为对于动态生成的页面,这可能会出现问题。

      • 以上内容适用于 OSX 10.8.4。未针对其他版本进行测试。

      【讨论】:

      • 谢谢,delay 很重要。
      【解决方案4】:

      这是一种保存充满标签的窗口的方法。最初的 UI 处理程序是由 StefanK aka 编写的。 Macscripter 的 Stefan Klieme 成名。它考虑了 webarchives 文件的结尾,当 Safari 有疑问时,您可以调整是否要覆盖或忽略已写入的文件。它不保存重复的选项卡,您可以设置一个属性来决定它是否在保存时关闭选项卡。

      请查看 MacScripter,脚本中有直接链接,以获取任何更新。

      你可以过度使用 wget,但我选择了 UI 脚本,因为 wget 可以下载已经在你的浏览器中的东西,并且也是编程的一个工具。

      房产证:我 # 发布 1.0.1 # © 2012 McUsr 并在 GPL 1.0 下放入公共领域 # 请参考这篇帖子:http://macscripter.net/post.php?tid=30892 property shallClose : false # 如果您不想关闭窗口,则将其设置为 false,只需保存它们 property dontOverWriteSavedTabs : false # 如果您不想覆盖文件夹中已保存的选项卡,请将此设置为 true 脚本 saveTabsInSafariWindowsToFolder 属性父:AppleScript 属性脚本标题:“SafariSaveTabs” 运行中 if downloadWindowInFront() then return 0 # 激活 Safari 本地脚本缓存 将 script_cache 设置为我存储的 scriptCache() 将 saveFolder 设置为 (getHFSFolder({theMessage:"Choose or create folder to save Safari-tabs in.", hfsPath:DefaultLocation of script_cache as alias})) 的 POSIX 路径 如果 saveFolder = false 则返回 0 - 我们显然弄错了,关于我们想要做什么。 我存储的 saveParenFolderInScriptCache(saveFolder, script_cache) 告诉应用程序“Safari” 告诉它的窗口 1 本地 tabc,oldidx 设置 tabc 来计算它的标签 If not tlvl's shallClose then 将 oldidx 设置为当前选项卡的索引 告诉 tab tabc 执行 JavaScript "self.focus()" 万一 本地保存计数器 将 saveCounter 设置为 1 -- 将保存文件夹的设置调整为仅在 Safari 中的第一次。 在 tabc > 0 时重复 本地 theUrl, theIdx, theProtocol, 已经关闭 将 {theUrl, theIdx, alreadyClosed} 设置为 {其当前选项卡的 URL,其当前选项卡的索引,false} 如果我的 isntAduplicateTab(theIdx, it) 那么 将协议设置为我的 urlprotocol(theUrl) 如果协议在 {"http", "https"} 那么 # 保存 将 saveCounter 设置为我的 saveCurrentTab(saveFolder, saveCounter) 否则如果协议是“文件”那么 # 为它创建一个别名 我的 makeAliasForAFurl(saveFolder, theUrl) 万一 别的 if tlvl's shallClose then 关闭当前标签 设置已经关闭为真 万一 万一 如果尚未关闭并且 tlvl 的 shallClose 则 关闭它的当前标签 将 tabc 设置为 tabc - 1 else if not tlvl's shallClose then 将 tabc 设置为 tabc - 1 如果 tabc > 0 然后告诉 tab tabc 执行 JavaScript "self.focus()" 万一 结束重复 # 向前移动 If not tlvl's shallClose then 告诉 tab oldidx 执行 JavaScript "self.focus()" 万一 结束告诉 结束告诉 结束运行 制作AliasForAFurl(destinationFolder, furl) 本地 ti、tids、文件路径 将 ti 设置为“file://” 将 {tids, AppleScript's text item delimiters} 设置为 {AppleScript's text item delimiters, ti} 将文件路径设置为 furl 的文本项 2 将 AppleScript 的文本项分隔符设置为 tids 将 theFile 设置为 POSIX 文件 thefilePath 作为别名 将文件夹设置为 POSIX 文件目标文件夹 告诉应用程序“Finder” 在theFolder为theFile创建别名 # 我不在乎以前是否有一个,因为它同样可以 # 是同名文件。 结束告诉 结束 makeAliasForAFurl 保存CurrentTab(destinationFolder, timeNumber) 告诉应用程序 ID“sfri”激活 告诉应用程序“系统事件” 将 UI 元素设置为 true 告诉进程“Safari” 使用 {command down} 击键“s” 告诉窗口 1 重复直到存在工作表 1 延迟 0.2 结束重复 告诉表 1 if timeNumber = 1 then -- 我们将在第一次调用时设置保存路径 使用 {command down, shift down} 击键“g” 重复直到存在工作表 1 延迟 0.2 结束重复 告诉表 1 将文本字段 1 的值设置为destinationFolder 点击按钮 1 延迟 0.1 结束告诉 万一 击键返回 延迟 0.2 如果存在工作表 1 则 - 我们被询问是否要覆盖已保存的选项卡 如果 dontOverWriteSavedTabs 然后 keystroke return # 如果它已经被保存。我们不会覆盖它 点击按钮 3 别的 击键选项卡 击键空间#我们要覆盖 万一 别的 尝试 将虚拟设置为工作表 1 的焦点 错误 # 单击应用程序“Safari”面板的按钮 1 击键返回 延迟 0.2 如果存在工作表 1 则 - 我们被询问是否要覆盖已保存的选项卡 如果 dontOverWriteSavedTabs 然后 keystroke return # 如果它已经被保存。我们不会覆盖它 点击按钮 3 别的 击键选项卡 击键空间#我们要覆盖 万一 万一 结束尝试 万一 结束告诉 结束告诉 结束告诉 结束告诉 将 timeNumber 设置为 timeNumber + 1 返回时间编号 结束 saveCurrentTab 在下载WindowInFront() 告诉应用程序“Safari” 启用 设置 tabCount 以计算其窗口 1 的选项卡 如果 tabCount 为 0,则将冒号设置为 true 如果(aPath 中“/”的偏移量)> 0,则将斜杠设置为 true 如果冒号和斜线则 返回空 else if 冒号 then 将 origDelims 设置为“:” else if 斜线 then 将 origDelims 设置为“/” 别的 返回空 万一 本地新闻 将 {tids, AppleScript's text item delimiters} 设置为 {AppleScript's text item delimiters, origDelims} 如果 aPath = "/" 那么 -- 当我们得到root时我们返回root 将 AppleScript 的文本项分隔符设置为 tids 返回 ”/” 万一 本地父文件夹 如果 aPath 的文本 -1 在 {":", "/"} 中,则 将父文件夹设置为文本项目 1 到 -2 的文本 1 到 -2 的 aPath 别的 将父文件夹设置为 aPath 的文本项 1 到 -2 万一 将父文件夹设置为父文件夹作为文本 如果斜杠和 theParentFolder = "" 则将 theParentFolder 设置为 "/" -- 如果我们有一个比它低一级的文件夹,则设置根路径 如果冒号和(“:”不在父文件夹中)则将父文件夹设置为父文件夹和“:” -- 我们返回卷名,如果给定卷名 将 AppleScript 的文本项分隔符设置为 tids 返回父文件夹 结束父文件夹 脚本存储 属性 cachespath : ((从用户域到库文件夹的路径作为文本) & "caches:" & "net.mcusr." & scripttitle) 在 scriptCache() 上 本地脚本缓存 尝试 设置 script_cache 加载脚本别名(我的缓存路径) 错误 脚本 newScriptCache 属性 DefaultLocation :(桌面文件夹的路径为文本) # 编辑任何具有默认值的值 结束脚本 将 script_cache 设置为 newScriptCache 结束尝试 返回脚本缓存 结束脚本缓存 保存ScriptCache(theCache) 在我的缓存路径中存储脚本 theCache 替换是 结束 saveScriptCache 保存ParenFolderInScriptCache(theFolderToSaveIn, script_cache) 本地包含文件夹 将 containsFolder 设置为(用于 theFolderToSaveIn 的 saveTabsInSafariWindowsToFolder 的父文件夹)和“/” 当地的 将 theLoc 设置为包含文件夹作为别名的 POSIX 文件 将 script_cache 的 DefaultLocation 设置为 theLoc 我的 saveScriptCache(script_cache) 结束 saveParenFolderInScriptCache 结束脚本 结束脚本 告诉 saveTabsInSafariWindowsToFolder 运行

      享受

      【讨论】:

        【解决方案5】:

        Automator 会这样做。这是工作流程 - http://cl.ly/450m0Q21463p16322P1i

        Automator -> 动作 -> 互联网 -> Get Current Webpage from Safari -> Download Urls.

        【讨论】:

          猜你喜欢
          • 2021-11-15
          • 1970-01-01
          • 1970-01-01
          • 2015-12-29
          • 1970-01-01
          • 2014-09-15
          • 1970-01-01
          • 1970-01-01
          • 2012-09-13
          相关资源
          最近更新 更多