错误“被调用的对象已与其客户端断开连接” - 使用python和win32com自动化IE 8
我想在Windows 7上用Python 2.7自动化Internet Explorer 8。以下是我根据StackOverflow上的一篇帖子写的代码:
import sys, time
from win32com.client import WithEvents, Dispatch
import pythoncom
import threading
stopEvent=threading.Event()
class EventSink(object):
def OnNavigateComplete2(self,*args):
print "complete",args
stopEvent.set()
def waitUntilReady(ie):
if ie.ReadyState!=4:
while 1:
print "waiting"
pythoncom.PumpWaitingMessages()
stopEvent.wait(.2)
if stopEvent.isSet() or ie.ReadyState==4:
stopEvent.clear()
break;
if __name__ == '__main__':
time.clock()
ie=Dispatch('InternetExplorer.Application',EventSink)
ev=WithEvents(ie,EventSink)
ie.Visible=True
ie.AddressBar = True
ie.Navigate("http://www.sap.com/austria/index.epx")
waitUntilReady(ie)
我在访问http://www.sap.com/austria/index.epx时收到了以下错误信息:
waiting
waiting
Traceback (most recent call last):
File "C:\Users\w\My Documents\Aptana Studio 3 Workspace\MyApp\src\GoToIdeaWindow.py", line 41, in <module>
waitUntilReady(ie)
File "C:\Users\w\My Documents\Aptana Studio 3 Workspace\MyApp\src\GoToIdeaWindow.py", line 26, in waitUntilReady
if stopEvent.isSet() or ie.ReadyState==4:
File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 463, in __getattr__
return self._ApplyTypes_(*args)
File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 456, in _ApplyTypes_
self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
pywintypes.com_error: (-2147417848, 'The object invoked has disconnected from its clients.', None, None)
这段代码在访问像google.com或bbc.com这样的网站时运行得很好。有没有人知道可能是什么原因呢?
4 个回答
2
哇,我这几天一直在跟一个脚本斗争,结果它连第10行都没执行。我发现微软在我们公司悄悄把Internet Explorer更新到了IE10,这给CRM开发人员带来了很大的麻烦。我注意到现在设置被重置为默认值,保护模式也被打开了。
在开发你的网站时,有一个非常有用的技巧就是按F12键,然后把IE的版本切换到其他版本。比如说,你的网站在IE9上能正常工作,但在IE10上就坏了。这样你就可以在IE10上运行,同时测试你的网站在多个版本下的表现。我还在寻找一种方法,能让某些网站在特定版本的Internet Explorer中打开,而不需要每次都按F12。
3
我无法更改我的IE安全设置,但我找到了另一个在VBScript中有效的解决方案(别问我为什么我在用这个 :D)!
http://go-gaga-over-testing.blogspot.co.uk/2013/06/the-object-invoked-has-disconnected.html
Set ie = WScript.CreateObject("InternetExplorer.Application")
With ie
hwnd = .hwnd
.Navigate theURL
End With
Set oShell = CreateObject("Shell.Application")
For Each Wnd In oShell.Windows
If hwnd = Wnd.hwnd Then Set ie = Wnd
Next
13
在IE9浏览器中,你需要降低安全设置才能让这个脚本正常工作:
IE9 -> Internet Options -> Security -> Trusted Sites : Low
IE9 -> Internet Options -> Security -> Internet : Medium + unchecked Enable Protected Mode
IE9 -> Internet Options -> Security -> Restricted Sites : unchecked Enable Protected Mode