Skip to main content
 首页 » 编程设计

Python:检查 IE 状态时出错

2025年05月04日13cmt

请帮助我使用 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??

请您参考如下方法:

sleep 技巧不适用于 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