Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: error while checking IE state

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??

like image 639
V.Aks Avatar asked Dec 04 '25 15:12

V.Aks


1 Answers

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
like image 133
Ryan Ginstrom Avatar answered Dec 07 '25 04:12

Ryan Ginstrom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!