在VBA中使用getElementByClassName

时间:2016-12-26 08:04:13

标签: excel vba excel-vba

我正在使用此代码从页面获取产品名称 页面代码是

<div class="product-shop col-sm-7">
<div class="product-name">
<h1 >Claro Glass 1.5 L Rectangular Air Tight Food Container with Lid- Clear GMA0215A</h1>
</div>

我的vba代码是

Public Sub GetValueFromBrowser()
Dim ie As Object
Dim name As String
Do Until IsEmpty(ActiveCell)
ActiveCell.Offset(0, 1).Value = "RUNNING"
URL = Selection.Value
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = 0
.navigate URL
While .Busy Or .readyState <> 4
DoEvents
Wend
End With
Dim Doc As HTMLDocument
Set Doc = ie.document
ActiveCell.Offset(0, 1).Value = "ERROR"
name = Trim(Doc.getElementByClassName("product-name").innerText)
ActiveCell.Offset(0, 1).Value = name
ie.Quit
Loop
End Sub

我得到的错误是

  

运行时错误'438':

     

Object不支持此属性或方法

2 个答案:

答案 0 :(得分:4)

GetElementsByClassName方法

您在方法getElement s ByClassName的名称中缺少s

  • 更改此name = Trim(Doc.getElementByClassName("product-name").innerText)
  • name = Trim(Doc.getElementsByClassName("product-name")(0).innerText)。优先选择您要定位的商品(0)

答案 1 :(得分:0)

仍然可以定义自己的函数getElementByClassName

当DOM文档中不存在具有此类名的元素时,此函数返回DOM文档中具有给定类名的第一个元素 Nothing

Public Function getElementByClassName(doc As MSHTML.HTMLDocument, className As String) As IHTMLElement
    Set getElementByClassName = doc.querySelector("[class='" & className & "']")
End Function

用法:

Dim elm As IHTMLElement
Set elm = getElementByClassName(doc, "product-name")

If Not elm Is Nothing Then
    Debug.Print elm.innerText
End If