我无法弄清楚如何使用getelementsbyclassname。我有以下标签。我可以通过执行(“div”)并列出其项目编号来进行getelementsbytagname,但我想在此实例中找到类名称项目2。在这里的网页上是标签。
<div class="column">
Projected Delivery Date:
</div>
<div class="column">
11/28/2017
</div>
我想在那里约会。这是我用来完成此任务的代码。它不与“partner_info组”或“列”一起使用。我遍历所有标签,它似乎没有拿起它。
Private Function TrackNEW(trackingNumber As String) As String
Dim xml As Object
Dim tempString As String
Dim htmlDoc As Object ' MSHTML.HTMLDocument
Dim htmlBody As Object ' MSHTML.htmlBody
Dim anchors As Object ' MSHTML.IHTMLElementCollection
Dim anchor As Object ' MSHTML.IHTMLElement
Dim dda As Object ' MSHTML.IHTMLElementCollection
Dim ddb As Object
Dim ddc As Object
Dim ddd As Object
Dim span As Object
Dim div As Object ' MSHTML.IHTMLElement
Set xml = GetMSXML
If xml Is Nothing Then ' cannot start MSXML 6.0
TrackNEW = MSXML_ERROR
Exit Function
End If
tempString = GetResponse(xml, HTTP_GET, NEWUrl & trackingNumber, False)
If Len(tempString) = 0 Then
TrackNEW = ERROR_MSG
Exit Function
End If
Set htmlDoc = CreateHTMLDoc
If htmlDoc Is Nothing Then ' cannot reference MSHTML object library
TrackNEW = MSHTML_ERROR
Exit Function
End If
Set htmlBody = htmlDoc.body
htmlBody.innerHtml = tempString
On Error Resume Next
Set dda = htmlDoc.getElementsByTagName("span")
Set ddb = htmlDoc.getElementsByTagName("span")
Set ddc = htmlDoc.getElementsByTagName("span")
Set ddd = htmlDoc.getElementsByClassName("column")
For Each Strg4 In ddd
For ItemNumber4 = 1 To 600
Strg4 = ddd.Item(ItemNumber4).innerText
If InStr(Strg4, "Projected Delivery Date:") >= 1 Then
Strg4 = ddd.Item(ItemNumber4).innerText
GoTo Line8
Else
End If
Next ItemNumber4
Next Strg4
MsgBox "Bad"
Exit Function
Line8:
TrackNEW = Strg4
Exit Function
如果有人能解释如何修复我的代码,那么它会提取日期吗?再一次,我可以为“div”做getelementsbytagname,但如果可能的话我想通过类名。我在Excel中使用VBA来执行此操作。这不是Java Script
答案 0 :(得分:0)
嗯,我得到了这个工作,它用class =“column”读取元素的innerText,所以看看你做了什么不同的改变,直到你可以让它工作。 此外,您必须在工具&gt;引用下将“Microsoft HTML Object Library”添加到项目中。
Sub sub1()
Dim hdoc As HTMLDocument
' your test HTML
sHtml = "<div class=""column"">" & vbCrLf & _
vbCrLf & _
"Projected Delivery Date:" & vbCrLf & _
vbCrLf & _
"</div>" & vbCrLf & _
vbCrLf & _
"<div class=""column"">" & vbCrLf & _
vbCrLf & _
"11/28/2017" & vbCrLf & _
"</div>"
Set hdoc = New HTMLDocument
hdoc.body.innerHTML = sHtml
For Each element In hdoc.getElementsByClassName("column")
Debug.Print element.innerText
Next
End Sub
答案 1 :(得分:0)
不确定为什么可以循环所有column
类的元素。当您找到一个值为Projected Delivery Date
的商品时,请在下一个索引处选择商品。
我使用CSS类选择器来获取所有匹配元素的nodeList
并将其循环。
Dim nodeList As Object, i As Long
If htmlDoc Is Nothing Then Exit Sub
Set nodeList =htmlDoc.querySelectorAll(".column")
For i = 0 To nodeList.Length - 1
If InStr(nodeList.item(i).innerText, "Projected Delivery Date") > 0 Then
Debug.Print nodeList.item(i + 1).innerText
Exit For
End If
Next