为避免阻塞问题,请在线程中使用 IE COM 对象。
这是一个简单但功能强大的示例,演示了如何同时使用线程和 IE com 对象。您可以根据自己的目的对其进行改进。
本例启动一个线程a使用队列与主线程通信,在主线程中用户可以将url添加到队列中,IE线程一个一个访问,完成一个url后,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)