vba 使用Excel VBA按类名查询div元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20129927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Query div element by class name using Excel VBA
提问by Nuno Nogueira
I'm trying to get the data to Excel of a div element with a specific class name, like:
我正在尝试将数据获取到具有特定类名的 div 元素的 Excel 中,例如:
<div class="myClass">
<span>Text1</span>
<span>Text2</span>
</div>
My VBA code:
我的 VBA 代码:
Sub GetData()
Dim oHtml As HTMLDocument
Dim oElement As Object
Set oHtml = New HTMLDocument
With CreateObject("WINHTTP.WinHTTPRequest.5.1")
.Open "GET", "http://www.example.com/", False
.send
oHtml.body.innerHTML = .responseText
End With
For Each oElement In oHtml.getElementsByClassName("myClass")
Debug.Print oElement.Children(0).src
Next oElement
End Sub
This is returning the error: Run-time error: '438': Object doesn't support this property or method. The error is on line Debug.Print ...
这将返回错误:运行时错误:'438':对象不支持此属性或方法。错误是在线 Debug.Print ...
I have activated the following refereces: Microsoft HTML Object Library Microsoft Internet Controls
我已激活以下参考: Microsoft HTML Object Library Microsoft Internet Controls
I want to be able to select the text on the first or second span and paste it on a cell, how can I do this?
我希望能够选择第一个或第二个跨度上的文本并将其粘贴到单元格上,我该怎么做?
回答by Nuno Nogueira
This worked for me:
这对我有用:
Dim oHtml As HTMLDocument
Dim oElement As Object
Set oHtml = New HTMLDocument
With CreateObject("WINHTTP.WinHTTPRequest.5.1")
.Open "GET", "http://www.example.com", False
.send
oHtml.body.innerHTML = .responseText
End With
Set dados = oHtml.getElementsByClassName("myClass")(0).getElementsByTagName("span")
i = 0
For Each oElement In dados
Sheets("Sheet1").Range("A" & i + 1) = dados(i).innerText
i = i + 1
Next oElement
回答by safetyOtter
Here's how I've done it in the past:
这是我过去的做法:
Set oElement = oHtml.getElementsByClassName("myClass")
i = 0
While i < oElement.Length
Debug.Print oElement(i).innerText
i = i + 1
Wend
you might want innerHtml instead?
你可能想要innerHtml?