How do you tell if Safari is done loading a page? There actually are quite a few ways and some work better than others. I’m largely following this hint. All the versions I’ve seen are in Applescript. I’ve not seen any in Python and Appscript though. (Note: I’ve only tested this against Safari 4 while the OSXHints post is about Safari 3 and the Safari 4 beta)
All I do is create a little function like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | def wait_Safari_done(): # wait for end of first failure while True: try: s = app(u'/System/Library/CoreServices/System Events.app').application_processes[u'Safari'].windows[1].groups[1].static_texts[1].name.get(resulttype=k.unicode_text) break except: time.sleep(1) continue # wait until second failure while True: try: s = app(u'/System/Library/CoreServices/System Events.app').application_processes[u'Safari'].windows[1].groups[1].static_texts[1].name.get(resulttype=k.unicode_text) print s print s[0:7] if s[0:7] == "Loading": continue print s[0:10] if s[0:10] == "Contacting": continue break except: time.sleep(1) |
Basically the idea is to call System Events and to get an information string with info about the front Safari window. Initially it says “Contacting X” where X is the name of the server. When Safari is still loading the web page then the string has “Loading” followed by the url of the window, “completed” and the number of parts of the document loaded.
The only trick is that if Safari isn’t at the stage to return this message you get an error when you try to contact System Events. But, and this is where it’s really weird, when Safari is finished loading you also get an error. (My impression is that this is a new response with Safari 4 – so it may change again in the future) To catch these errors we use exceptions. I could probably take out the check to see if the beginning of the string says, “Loading”. That’s primarily just sanity checking and because you might wish to distinguish between the contacting phase and loading phases.
If you were writing a full GUI in Python you could extract enough information from this to put up a process bar. (Unlike Safari 4 which took the process bar out)
Related posts:
.jpg)
#1 by clark on 2009/08/24 - 10:43 am
Inexplicably the above doesn’t work on PPC machines. (Yes, I just spent the last hour butting my head against this for something at work)
Replace def wait_Safari_done() in the above with this:
You could probably take out that “for” in the above with a “while True” but I just liked there to be a limit so I don’t end up in an infinite loop.
#2 by clark on 2010/02/05 - 11:19 pm
Just a note that Safari tends to change a lot relative to the above. I’ve put a permanent link to the latest version of this script up in my Address Book to FedEx script. Look at module paste_to_fedex.py and the function check_Safari_done().