Interesting "getElementById() takes exactly 1 argument (2 given)", sometimes it occurs. Can someone explain it?

Tre Mi picture Tre Mi · Mar 22, 2012 · Viewed 7.9k times · Source
#-*- coding:utf-8 -*-
import win32com.client, pythoncom
import time

ie = win32com.client.DispatchEx('InternetExplorer.Application.1')
ie.Visible = 1
ie.Navigate('http://ieeexplore.ieee.org/xpl/periodicals.jsp')
time.sleep( 5 )

ie.Document.getElementById("browse_keyword").value ="Computer"
ie.Document.getElementsByTagName("input")[24].click()

import win32com.client, pythoncom
import time

ie = win32com.client.DispatchEx('InternetExplorer.Application')
ie.Visible = 1
ie.Navigate('www.baidu.com')
time.sleep(5)

print 'browse_keword'
ie.Document.getElementById("kw").value ="Computer"
ie.Document.getElementById("su").click()
print 'Done!'

When run the first section code,it will popup:

ie.Document.getElementById("browse_keyword").value ="Computer"
TypeError: getElementById() takes exactly 1 argument (2 given)

And the second section code runs ok. What is the difference that making the result different?

Answer

Duncan picture Duncan · Feb 11, 2013

The difference between the two cases has nothing to do with the COM name you specify: either InternetExplorer.Application or InternetExplorer.Application.1 result in the exact same CLSID which gives you an IWebBrowser2 interface. The difference in runtime behaviour is purely down to the URL you retrieved.

The difference here may be that the page which works is HTML whereas the other one is XHTML; or it may simply be that errors in the failing page prevent the DOM initialising properly. Whichever it appears to be a 'feature' of the IE9 parser.

Note that this doesn't happen if you enable compatibility mode (after the second line below I clicked the compatibility mode icon in the address bar):

(Pdb) ie.Document.DocumentMode
9.0
(Pdb) ie.Document.getElementById("browse_keyword").value
*** TypeError: getElementById() takes exactly 1 argument (2 given)
(Pdb) ie.Document.documentMode
7.0
(Pdb) ie.Document.getElementById("browse_keyword").value
u''

Unfortunately I don't know how to toggle compatibility mode from a script (the documentMode property is not settable). Maybe someone else does?

The wrong argument count is, I think, coming from COM: Python passes in the arguments and the COM object rejects the call with a misleading error.