tags:

views:

59

answers:

3

Is there a way to determine programmatically, using Python, which web page is currently active in Safari?

A: 

May I suggest mind reading. One program usually cannot infer the inner state of another program.

But maybe you could write a bookmarklet (in JavaScript!) to expose the information to Python when clicked.

Jan B. Kjeldsen
@Jan, in Mac OS X properly coded applications can (reasonably easily) "mind read" each other, as you put it, thanks to OSA, Apple's scripting architecture. This is mainly intended for AppleScript, Apple's proprietary and peculiar scripting language, but as I show in my answer third party modules such as appscript make it pretty easy to access that wealth of functionality from Python too!
Alex Martelli
A: 

I don't know how to do this, but I would start here.

telliott99
+5  A: 

An Applescript example is here, and the relevant part is:

tell application "Safari"
    set url_list to URL of every document
end tell

Python/AppleScript translation is covered here. E.g., install appscript as described here:

sudo easy_install appscript

and then, as shown here, you can do e.g.:

>>> import appscript
>>> print appscript.app("Safari").windows.first.current_tab.URL()
http://wiki.python.org/moin/MacPython/Safari
Alex Martelli
Thank you! Unequivocally and precisely what I was looking for!
Chris Redford
@credford, you're welcome!
Alex Martelli
@Alex One caveat of this solution is that whenever I have it running a Python application icon pops up bouncing in the dock. If I close the application, it closes my python script, so I know the two are related. I'm wondering if you know a way for me to run the script without getting the Python program in the dock.
Chris Redford
Does the bouncing happen if you are running your script with a `Terminal.app`? Or how else are you packaging your `.py` file to obtain the "unwanted bounce" effect?
Alex Martelli
It happens whether I run the `.py` script in `Terminal.app`, `TextMate.app`, or as a `launchd` agent. And just so it is unambiguous, the primary problem is that I don't want Python to be in the dock (i.e. I want the script to run quietly in the background).
Chris Redford
@credford, I'm perplexed -- I run py scripts in Terminal all the time and don't see the bounce. Don't think we can solve it in these cramped comment boxes:-(. Please open another Q giving a minimal example that bounces when run from the terminal and both myself and others will strive to help, as usual on SO -- thanks.
Alex Martelli
@Alex Thanks! I'll post a question withen the next few days.
Chris Redford