在VBA中使用getElementByClassName

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

<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”:

对象不支持这个属性或方法

GetElementsByClassName方法

您在方法getElement ByClassName名称中缺lesss

  • 改变这个name = Trim(Doc.getElementByClassName("product-name").innerText)
  • 为此name = Trim(Doc.getElementsByClassName("product-name")(0).innerText) 。 将(0)replace为您定位的物品。

仍然可以定义你自己的函数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