VBA GetElementsByClassName获取错误5002

时间:2018-08-08 16:20:27

标签: html excel vba getelementsbyclassname

我第一次问一个问题,所以我们开始吧。

我有一些VBA经验,但是现在我已经被要求做一些我已经阅读过的Web抓取工作,并且还需要对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

似乎没有任何作用,所以我不知道自己没看到什么。

谢谢!

1 个答案:

答案 0 :(得分:0)

您是否尝试过应用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选择器:

query