views:

178

answers:

1

Please, help me with Python 2.6 and win32com.

I'm a newbie to Python and I got error when I start the next program:

import pywintypes
from win32com.client import Dispatch
from time import sleep

ie = Dispatch("InternetExplorer.Application")
ie.visible=1
url='hotfile.com'

ie.navigate(url)
while ie.ReadyState !=4:
    sleep(1)
print 'OK'
..........................
Error message:
 while ie.ReadyState !=4:
 ...

pywintypes.com_error: 
(-2147023179, 'Unknown interface.', None, None)
..........................

But when I change url to, for example, 'yahoo.com' - there are no errors.
How can result of checking ReadyState may be dependant on url??

+1  A: 

The sleep trick won't work with IE. You actually need to pump messages while you wait. I don't think a thread will work, by the way, because IE hates to not be in the GUI thread.

Here's a ctypes-based message pump, with which I was able to get a 4 ReadyState for "hotfile.com" and "yahoo.com". It pulls all the messages currently on the queue, and processes them before running the check.

(Yes, this is pretty hairy, but you can tuck this away into a "pump_messages" function so you at least don't have to look at it!)

from ctypes import Structure, pointer, windll
from ctypes import c_int, c_long, c_uint
import win32con
import pywintypes
from win32com.client import Dispatch

class POINT(Structure):
    _fields_ = [('x', c_long),
                ('y', c_long)]
    def __init__( self, x=0, y=0 ):
        self.x = x
        self.y = y

class MSG(Structure):
    _fields_ = [('hwnd', c_int),
                ('message', c_uint),
                ('wParam', c_int),
                ('lParam', c_int),
                ('time', c_int),
                ('pt', POINT)]

msg = MSG()
pMsg = pointer(msg)
NULL = c_int(win32con.NULL)

ie = Dispatch("InternetExplorer.Application")
ie.visible=1
url='hotfile.com'
ie.navigate(url)

while True:

    while windll.user32.PeekMessageW( pMsg, NULL, 0, 0, win32con.PM_REMOVE) != 0:
        windll.user32.TranslateMessage(pMsg)
        windll.user32.DispatchMessageW(pMsg)

    if ie.ReadyState == 4:
        print "Gotcha!"
        break
Ryan Ginstrom
Thank you, I'll try your code.But the strange thing (for me) is that sleep(1) work with IE,when navigating to other URLs, excluding hotfile.com...
V.Aks
It's probably a timing issue, and it's never a good idea to rely on timing issues.
Ryan Ginstrom