I am trying to convert some of my working VBA code to VBScript, but keep getting errors in VBScript when trying to use the getElementsByClassName method. Here\'s the full co
I took some time to elaborate a working example. Thanks to GSerg for pointing out the load delay. That is accurate. Had to tweak the code a little to get it working though. Based on the previous comments, maybe the behaviour of MSHTML depends on the code being parsed. Hence the aditional meta tag below.
Set objHTTP = CreateObject("MSXML2.XMLHTTP")
Dim htmldoc: Set htmldoc = CreateObject("htmlfile")
'
URL = "https://stackoverflow.com/questions/44853941/vbscript-getelementsbyclassname-not-supported"
' sEnv = ""
'
objHTTP.Open "GET", URL, False
' objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objHTTP.send ' (sEnv)
ttext = objHTTP.responsetext
ttext = "<meta http-equiv=""X-UA-Compatible"" content=""IE=EDGE,chrome=1"" />" & vbnewline & ttext
htmldoc.write ttext
htmldoc.close
htmldoc.designMode = "on" ' Refer to https://developpaper.com/method-of-parsing-html-documents-by-vbs-htmlfile/
WScript.ConnectObject htmldoc, "htmldoc_"
Sub htmldoc_onreadystatechange()
If htmldoc.readyState = "interactive" Then
ttext = htmldoc.getElementsByClassName("fs-headline1").Item(0).innerText
msgbox ttext
Wscript.quit
End If
End Sub
'-----------------
Wscript.Sleep 10000 ' Random timeout
msgbox "Timeout!"
MSHTML behaves differently depending on how it was instantiated - it exposes different interfaces depending on whether or not its early or late bound (its heavily reliant on IDispatch
).
You are late binding and no interface exposing getElementsByClassName
is available.
You can loop over document.all()
and look at each item.className
.
I used similar code to retrieve data from a POST request. getElementsByClassName worked only if preceded with another command, like "msgbox 1" or anything to halt the script for a fraction of a second. Then I tried Wscript.Sleep 200, decreasing it to the smallest possible number, and it still worked.
Wscript.Sleep 1 ' This line got it working.
msgbox html.getElementsByClassName("match-info-box-con")(0).innertext'