getElementById FirstChild抛出运行时错误91

时间:2016-05-24 17:19:20

标签: excel vba

我正在尝试使用MSXML2类登录网站并将价格下载到我的电子表格中。我有一个产品编号列表,代码用来搜索产品,然后它应该从html中提取price元素。

我的问题是我不断收到“对象变量或未设置块变量”错误,没有多少论坛潜水给我一个解决方案。

错误发生在document.getElementById("prix").FirstChild.innerHTML = .responseText

    Option Explicit

Function loginRematek()

 Dim XMLHttpRequest As New MSXML2.XMLHTTP60
 Dim xhr As MSXML2.XMLHTTP60
 Dim cell As Integer
 Dim ItemNbr As String
 Dim document As MSHTML.HTMLDocument

    'Login to Rematek
  With XMLHttpRequest
   .Open "POST", "https://rematek-energie.com/eng/customer-login/account- authentication.php", False
   .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
   .send "name_se_connecter=se_connecter&zebra_honeypot_se_connecter=&courriel=rob@solacity.com&motpasse=password&connexion=Sign in"
  End With

  Debug.Print XMLHttpRequest.responseText

    'Get Element
  Set xhr = New MSXML2.XMLHTTP60

  For cell = 1 To 38

      ItemNbr = Cells(cell, 1).Value

      With xhr

          .Open "GET", "https://rematek-energie.com/eng/pg/1/r/" & ItemNbr, False
          .send

          If .readyState = 4 And .Status = 200 Then
              Set document = New MSHTML.HTMLDocument
              document.getElementById("prix").FirstChild.innerHTML = .responseText
          Else
              MsgBox "Error" & vbNewLine & "Ready state: " & .readyState & _
              vbNewLine & "HTTP request status: " & .Status
          End If

      Cells(cell, 2).Value = .responseText

      End With

    Next cell
End Function

同样,错误发生在document.getElementById("prix").FirstChild.innerHTML = .responseText

我尝试定位的HTML是panier_prix_326值,但ID会在每个页面上发生变化,因为我定位多个页面,我认为最好首先定位常量{{1}然后是该元素的第一个孩子。

prix

1 个答案:

答案 0 :(得分:3)

Set document = New MSHTML.HTMLDocument
document.getElementById("prix").FirstChild.innerHTML = .responseText

document是一个空的HTML文档 - 没有内容可供选择。

这可能是你想要的:

If .readyState = 4 And .Status = 200 Then
    Set document = New MSHTML.HTMLDocument
    document.body.innerHTML = .responseText 
    Cells(cell, 2).Value = _
                  document.getElementById("prix").FirstChild.innerHTML
Else
    MsgBox "Error" & vbNewLine & "Ready state: " & .readyState & _
            vbNewLine & "HTTP request status: " & .Status
End If

编辑 - 您的HTML没有ID“prix”,因此您无法在此处使用getElementById

<tr>
    <td id="col-action">
        <div class="prix">
            <span id="panier_prix_326">99.40</span>
            <div id="prix-detail">MSRP: 152.93$</div>
        </div>
    </td>
</tr>

也许相反:

Cells(cell, 2).Value = _
 document.getElementById("col-action").getElementsByTagName("span")(0).innerText