3

请帮助我使用 Python 2.6 和 win32com。

我是 Python 的新手,在启动下一个程序时出现错误:

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)
..........................

但是,当我将 url 更改为例如“yahoo.com”时 - 没有错误。
检查 ReadyState 的结果如何可能取决于 url?

4

1 回答 1

1

睡眠技巧不适用于 IE。您实际上需要在等待时发送消息。顺便说一句,我认为线程不会起作用,因为 IE 讨厌不在 GUI 线程中。

这是一个基于ctypes的消息泵,通过它我能够为“hotfile.com”和“yahoo.com”获得 4 ReadyState。它提取当前队列中的所有消息,并在运行检查之前对其进行处理。

(是的,这很麻烦,但你可以把它塞进一个“pump_messages”函数中,这样你至少不必看它!)

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
于 2009-12-27T14:36:52.680 回答