使用VBA从Web文档input元素获取价值

我很难从名为points的input中检索值300

这是我的HTML和VBA代码。

HTML

 <td id="myPower_val_9" style="visibility: visible;"> <input type="text" disabled="disabled" value="300" name="points"></input> </td> 

VBA

 Dim ie As Object Dim myPoints As String Set ie = CreateObject("InternetExplorer.Application") With ie .Visible = 0 .navigate "www.example.com" While .Busy Or .readyState <> 4 DoEvents Wend End With Dim Doc As HTMLDocument Set Doc = ie.document myPoints = Trim(Doc.getElementsByTagName("td")(0).getElementById("myPoints").innerText) Range("A1").Value = myPoints 

HTML代码

我会尝试在Web浏览器中处理JavaScript中处理文档对象模型(DOM)的代码,以便您可以使用更好的基于Web的debugging工具。

这里有几个问题 ,控制台或debugging器可以帮助:

  • 你想获得元素ID myPoints但在HTML中,它只是被称为points
  • 你想通过ID获取元素,但是你只需要设置name属性 –
  • 只要name是元素唯一的,就不需要首先searchtd
  • <input></input>可以看到,input元素没有innerText><的文本)。 相反,他们有一个value属性
  • 元素通过对象本身的属性公开属性和其他数据。 所以你可以通过查看.value来检查input的值

以下是您要做的一个JavaScript示例:

 var value = document.getElementsByName("points")[0].value; console.log(value); 
 <input type="text" disabled="disabled" value="300" name="points" /> 

您需要使用.getAttribute("name of attribute")来获取属性值。 在你的情况.getAttribute("value")将返回300。

 Dim ie As Object Dim myPoints As String Set ie = CreateObject("InternetExplorer.Application") With ie .Visible = 1 .navigate "website URL" While .Busy Or .readyState <> 4 DoEvents Wend End With Dim Doc As HTMLDocument Set Doc = ie.document myPoints = Trim(Doc.getElementsByTagName("td")(0).getElementsByTagName("input")(0).getAttribute("value")) Range("A1").Value = myPoints 

只是在一个侧面说明。 我不太了解HTML,也许有人可以详细说明这一点。 但是,如果要testing该HTML代码,则需要在<table> <tr>标记中添加。
像这样的东西:

 <table> <tr> <td id="myPower_val_9" style="visibility: visible;"> <input type="text" disabled="disabled" value="300" name="points"></input> </td> </tr> </table>