using getElementByClassName in VBA

2019-07-10 06:30发布

I am using this code to get product name from a page code of page is

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

my vba code is

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

error i am getting is

run-time error '438':

Object doesn't support this property or method

2条回答
贼婆χ
2楼-- · 2019-07-10 07:17

GetElementsByClassName method

You are missing an s in the name of the method getElementsByClassName.

  • Change this name = Trim(Doc.getElementByClassName("product-name").innerText)
  • To this name = Trim(Doc.getElementsByClassName("product-name")(0).innerText). Substitude the (0) for the item you are targeting.
查看更多
Viruses.
3楼-- · 2019-07-10 07:26

It is still possible to define your own function getElementByClassName.

This function returns the very first element with given class name in the DOM document and Nothing when no element with this class name exist in the DOM document.

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

Usage:

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

If Not elm Is Nothing Then
    Debug.Print elm.innerText
End If
查看更多
登录 后发表回答