如何关闭不响应的 Win32 Internet Explorer COM 接口?
其实这不是卡住的状态,我的意思是它反应很慢,
所以在这种情况下,
我想关闭IE浏览器,然后从头再来。
关闭没有问题,问题是,怎么设置超时时间,比如我设置15秒,
如果网页在15秒内没有打开,我就想关闭它,然后重新开始。
这样做在IE的COM接口中可以实现吗?
真的很难找到解决办法。
保罗,
我习惯通过代码来检查一个网页是否完全打开。
但正如我提到的,这个方法效果不好,因为IE.navigate看起来像是卡住了或者没有反应。
while ie.ReadyState != 4:
time.sleep(0.5)
1 个回答
0
为了避免阻塞问题,可以在一个线程中使用IE的COM对象。
下面是一个简单但很有效的例子,展示了如何将线程和IE的COM对象结合使用。你可以根据自己的需要进行改进。
这个例子启动了一个线程,并使用队列与主线程进行通信。在主线程中,用户可以将网址添加到队列中,而IE线程会一个一个地访问这些网址。当IE访问完一个网址后,就会去访问下一个。由于IE的COM对象是在一个线程中使用的,所以你需要调用Coinitialize。
from threading import Thread
from Queue import Queue
from win32com.client import Dispatch
import pythoncom
import time
class IEThread(Thread):
def __init__(self):
Thread.__init__(self)
self.queue = Queue()
def run(self):
ie = None
# as IE Com object will be used in thread, do CoInitialize
pythoncom.CoInitialize()
try:
ie = Dispatch("InternetExplorer.Application")
ie.Visible = 1
while 1:
url = self.queue.get()
print "Visiting...",url
ie.Navigate(url)
while ie.Busy:
time.sleep(0.1)
except Exception,e:
print "Error in IEThread:",e
if ie is not None:
ie.Quit()
ieThread = IEThread()
ieThread.start()
while 1:
url = raw_input("enter url to visit:")
if url == 'q':
break
ieThread.queue.put(url)