如何在继续脚本之前等待网页完全加载?

时间:2014-06-30 22:42:20

标签: applescript

在继续编写脚本之前,如何等待网页完全加载?

我知道你可以使用延迟4,如果你想让它等待4秒但这还不够安全。

在VBA中,你有一个总是有效的简单代码,它是这样的:

Dim x As String
x = "https://na6.salesforce.com/p/attach/NoteAttach?pid=" & Range("T34").Value & "&parentname=" & Range("T35").Value & "&retURL=%2F0018000000sKz8K%3Fpb0%3Dtrue"

   Set IE = CreateObject("InternetExplorer.Application")
    IE.Navigate (x)
    IE.Visible = True
    SetParent IE.Hwnd, Application.Hwnd

Do
DoEvents
Loop Until IE.READYSTATE = 4

在mac上使用safari for applescript会有什么相同的东西?

我在网上看到过很多版本,但只有类似于延迟或指定值的解决方法才能返回或计算页面上的文字等等。

我只想要100%完美的上述版本。

提前谢谢你:)

3 个答案:

答案 0 :(得分:3)

您可以通过从Safari或Chrome调用“document.readyState”来访问页面的就绪状态。

tell application "Safari"
    if not (exists document 1) then reopen
    tell current tab of window 1 to set URL to "https://stackoverflow.com/questions/24500011/how-to-wait-for-webpage-to-fully-load-before-proceeding-script"

    set the_state to missing value
    repeat until the_state is "complete"
        set the_state to (do JavaScript "document.readyState" in document 1)
        log "busy"
        delay 0.2
    end repeat
    log "complete"
end tell

答案 1 :(得分:2)

我是这样做的:

tell document 1 of application "Safari"  
  set URL to ""  
  set URL to "/slowly loading page/"  
  repeat until name is not "about:blank"  
  end repeat  
end tell

或者,更简单:

tell front document of application "Safari"  
  set URL to "/slowly loading page/"  
  repeat until length of (source as text) is not 0  
  end repeat  
end tell

此外,没有必要毫不拖延地做到这一点:

repeat until length of (source as text) is not 0  
  delay 0.5  
end repeat

答案 2 :(得分:1)

搜索了一下,发现此代码适用于Snow Leopard上的Safari版本5.1.10(6534.59.10)。

来自http://macscripter.net/viewtopic.php?id=35176

tell application "Safari"
   activate
   repeat until SafariWindowHasLoaded(1) of me is true
   end repeat
   beep
end tell

on SafariWindowHasLoaded(inWindowIndex)
   tell application "System Events" to ¬
       tell application process "Safari"    
           set theStatusText to name of static text 1 of group 1 of window inWindowIndex as text
           if theStatusText begins with "Contacting" or ¬
               theStatusText begins with "Loading" or ¬
               theStatusText begins with "Waiting" then
               set theReturnValue to false
           else
               set theReturnValue to true
           end if
       end tell
   return theReturnValue
end SafariWindowHasLoaded

我遇到的唯一问题是这个脚本是针对较早版本的Safari而且状态栏元素与我的不同。

http://hints.macworld.com/article.php?story=20071015132722688,建议将其更改为

static text 1 of group 2

它有效!