3

我的 Applescript 在 Safari 中(偶尔)遇到此错误。

Result:
   error "Safari got an error: Can’t get document \"DOC TITLE\"." 
   number -1728 from document "DOC TITLE"

我认为这是因为页面没有加载,但我有一个 Javascript 来检查“完成”,然后再继续,还有一个 try 语句可以在出错时再延迟一秒。

尽管如此,我仍然遇到这个问题。这似乎是相当随机的。

有什么建议么?

Applescript(整个 Tell 语句):

tell application "Safari"
set the URL of the front document to searchURL
delay 1
repeat
    if (do JavaScript "document.readyState" in document 1) is "complete" then exit repeat
    delay 1.5 -- wait a second before checking again
end repeat
try
    set doc to document "DOC TITLE"
on error
    delay 1
    set doc to document "DOC TITLE"
end try
set theSource to source of doc
set t to theSource
end tell
4

1 回答 1

5

您的代码中存在缺陷。首先你检查readyState,你怎么知道你正在检查正确文档的readyState?它可能是以前的文件。延迟 1 将显着缩短机会,但仍然不安全。我的第一个建议是在检查页面标题后检查 readyState。

然后,当首先检查页面标题时也会产生错误空间,我们有可能匹配上一页的页面标题(如果那是同一页面,或者至少具有相同的标题)。为了确保我们正在等待正确的页面标题,这是最简单的方法,首先将页面设置为“about:blank”。

另一件事,如您所见,我所做的是每个阶段不再等待超过 20 秒来加载页面。这是加载页面的更可控的方式:

tell application "Safari"
    -- first set the page to "about:blank"
    set the URL of the front document to "about:blank"
    set attempts to 1
    repeat until "about:blank" is (name of front document)
        set attempts to attempts + 1
        if attempts > 20 then -- creating a timeout of 20 seconds
            error "Timeout while waiting for blank page" number -128
        end if
        delay 1
    end repeat

    -- now we start from a blank page and open the right url and wait until page is loaded
    set the URL of the front document to searchURL
    set attempts to 1
    repeat until "DOC TITLE" is (name of front document)
        set attempts to attempts + 1
        if attempts > 20 then -- creating a timeout of 20 seconds
            error "Timeout while waiting for page" number -128
        end if
        delay 1
    end repeat

    -- now check the readystate of the document
    set attempts to 1
    repeat until (do JavaScript "document.readyState" in document 1) is "complete"
        set attempts to attempts + 1
        if attempts > 20 then -- creating a timeout of 20 seconds
            error "Timeout while waiting for page" number -128
        end if
        delay 1
    end repeat

    -- page should be loaded completely now
    set doc to document "DOC TITLE"
    set theSource to source of doc
    set t to theSource
end tell 
于 2014-03-20T16:11:24.427 回答