Recipe 10.15. Connecting to an Already Running Instance of Internet Explorer
Credit: Bill Bell, Graham Fawcett
Problem
Instantiating
Internet Explorer to access its interfaces via COM is easy, but you
want to connect to an already running instance.
Solution
The simplest approach is to rely on Internet
Explorer's CLSID:
from win32com.client import Dispatch
ShellWindowsCLSID = '{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'
ShellWindows = Dispatch(ShellWindowsCLSID)
print '%d instances of IE' % len(shellwindows)
for shellwindow in ShellWindows :
print shellwindow
print shellwindos.LocationName
print shellwindos.LocationURL
Discussion
Dispatching on the CLSID provides a sequence of all the running
instances of the application with that class. Of course, there could
be none, one, or more. If you're interested in a
specific instance, you may be able to identify it by checking, for
example, for its properties LocationName and
LocationURL.You'll see that Windows Explorer and Internet
Explorer have the same CLSIDthey're basically
the same application. If you need to distinguish between them, you
can try adding at the start of your script the statement:
from win32gui import GetClassNameand then checking each shellwindow in the loop with:
if GetClassName(shellwindow.HWND) == 'IEFrame':'IEFrame' is supposed to
...
result from this call (according to the docs) for all Internet
Explorer instances and those only. However, I have not found this
check to be wholly reliable across all versions and patch levels of
Windows and Internet Explorer, so, take this approach as just one
possibility (which is why I haven't added this check
to the recipe's official
"Solution").This recipe does not let you receive IE events. The most important
event is probably DocumentComplete. You can
roughly substitute checks on the Busy property for
the inability to wait for that event, but remember not to poll too
frequently (for that or any other property) or you may slow down your
PC excessively. Something like:
while shellwindow.Busy:Sleeping 0.2 seconds between checks may be a reasonable compromise
time.sleep(0.2)
between responding promptly and not loading your PC too heavily with
a busy-waiting-loop.
See Also
PyWin32 docs at http://sourceforge.net/projects/pywin32/;
Microsoft's MSDN site, http://msdn.microsoft.com.