"无法获取文档"错误 - Javascript和Applescript

pia*_*man 3 javascript safari applescript applescript-excel applescript-objc

我的Applescript在Safari中遇到了这个错误(偶尔).

Result:
   error "Safari got an error: Can’t get document \"DOC TITLE\"." 
   number -1728 from document "DOC TITLE"
Run Code Online (Sandbox Code Playgroud)

我认为这是因为页面没有加载,但我有一个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
Run Code Online (Sandbox Code Playgroud)

dj *_*zie 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 
Run Code Online (Sandbox Code Playgroud)