VBScript GetElementsByClassName not supported?

后端 未结 3 519
一生所求
一生所求 2020-12-11 11:39

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

相关标签:
3条回答
  • 2020-12-11 11:52

    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!"
    
    0 讨论(0)
  • 2020-12-11 12:04

    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.

    0 讨论(0)
  • 2020-12-11 12:09

    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'
    
    0 讨论(0)
提交回复
热议问题