首页 > 解决方案 > VBA GetElementsByClassName 得到错误 5002

问题描述

我第一次问问题,所以我们开始..

我在 VBA 方面有一些经验,但现在我被要求对我一直在阅读的内容进行一些网络抓取,并在 HTML 方面进行一些研究。问题是我有一个我无法解决的问题。

我需要做的事情真的没有困难..只需单击按钮或输入表单等一些元素自动完成,但这是我无法访问的:

<div class="dojoPopupMenu2" style="left: 31px; top: 293px; z-index: 1001;" dojoattachpoint="containerNode">
 <ul dojoattachpoint="containerNode">
  <li class="dojoMenuItem2 " dojoattachevent="onMouseOver: onHover; onMouseOut: onUnhover; onclick: _onclick; onKey:onKey;" dojoinsertionindex="0"><span tabindex="-1" class="dojoMenuItem2Label">1</span></li>
 <li class="dojoMenuItem2 " dojoattachevent="onMouseOver: onHover; onMouseOut: onUnhover; onclick: _onclick; onKey:onKey;" dojoinsertionindex="1"><span tabindex="-1" class="dojoMenuItem2Label">2</span></li>
 <li class="dojoMenuItem2 " dojoattachevent="onMouseOver: onHover; onMouseOut: onUnhover; onclick: _onclick; onKey:onKey;" dojoinsertionindex="2"><span tabindex="-1" class="dojoMenuItem2Label">3</span></li>
 <li class="dojoMenuItem2" dojoattachevent="onMouseOver: onHover; onMouseOut: onUnhover; onclick: _onclick; onKey:onKey;" dojoinsertionindex="3"><span tabindex="-1" class="dojoMenuItem2Label">4</span></li>
 <li class="dojoMenuItem2" dojoattachevent="onMouseOver: onHover; onMouseOut: onUnhover; onclick: _onclick; onKey:onKey;" dojoinsertionindex=`enter code here`"4"><span tabindex="-1" class="dojoMenuItem2Label">5</span>
 </li>
</ul>
</div>

有一个名为“添加项目”的前一个按钮,当它被点击时,你会得到一个带有数字 1 到 5 的下拉列表(上面的代码),这就是我需要选择的......这些数字取决于一些简单的条件

我已经尝试了这些选项,但似乎没有一个有效

Dim ieApp As Object
Dim ieDoc As Object
Dim ieEl As HTMLDivElement
Dim ieEls As HTMLObjectElement
Dim direccion As String
Set ieApp = CreateObject("InternetExplorer.Application")

With ieApp
For Each element In .document.getElementsByTagName("div") 'Tried with the tag "li" as well
    if element.classname = "dojoMenuItem2" Then
        'set a variable with the number 1 to 5 from the list (depending on other condition)
    end if
Next
End With


'also tried this
Dim additems as HTMLDivElement
Set additems = ieDoc.GetElementsByClassName("dojoMenuItem2")(0)
'this gets Automate error

'also tried this
Dim additems as HTMLDivElement
Set additems = ieDoc.GetElementsByClassName("dojoPopupMenu2")(0)
'this gets Automate error

似乎没有任何效果,所以我不知道我没有看到什么。

谢谢!

标签: htmlexcelvbagetelementsbyclassname

解决方案


您是否尝试过应用 CSS 属性选择器?

ieApp.document.querySelectorAll("[dojoinsertionindex]")  

属性选择器[dojoinsertionindex]将返回所有具有属性的元素[dojoinsertionindex]

这将返回一个nodeList您可以索引的内容。

或循环长度:

Dim aNodeList As Object, i As Long
Set aNodeList = ie.document.querySelectorAll("[dojoinsertionindex]")  
For i = 0 To aNodeList.Length-1
    Debug.Print aNodeList.item(i).innerText '< === as check
Next i

单击一个部分索引(从 0 开始为 1)

aNodeList.item(0).Click

HTML 示例中的 CSS 选择器:

询问


推荐阅读