如何使用vba在<ul>的<li>的<li>的<a>元素上单击?

时间:2019-06-17 15:34:17

标签: html excel vba

这是我正在处理的HTML页面的一段代码。 enter image description here

我正在尝试编写一个VBA代码,该代码单击上图中以蓝色突出显示的元素。

这是我写的代码:

Set objIE = New SHDocVw.InternetExplorer
Do While objIE.Busy: DoEvents: Loop
Do Until objIE.readyState = READYSTATE_COMPLETE: DoEvents: Loop

Set IeDoc2 = objIE.Document
Set the_input_elements2 = IeDoc2.getElementsByClassName("parent-item")

For Each input_element2 In the_input_elements2
    If input_element2.href = "javascript:directToSearch()" Then
        input_element2.Click
        Exit For
    End If
Next input_element2

我是VBA的新手,我不知道这是否是使用VBA在HTML中单击ul元素的正确方法。 当我运行此代码时,什么也没有发生。没有错误,但没有结果。

如果您能帮助我,我将非常高兴。

谢谢:)

2 个答案:

答案 0 :(得分:0)

在左侧菜单的ID中环绕所有“ a”标签

IeDoc2.getElementById("accordion-leftmenu").getElementsByTagName("a")

在循环中检查.innerText是否为“高级搜索”。请点击。

Dim IeDoc2 As MSHTML.HTMLDocument
Dim the_input_elements2 As MSHTML.IHTMLElementCollection
Dim input_element2 As MSHTML.IHTMLElement

...

Set the_input_elements2 = IeDoc2.getElementById("accordion-leftmenu").getElementsByTagName("a")

For Each input_element2 In the_input_elements2
    If input_element2.innerText = "Advanced Search" Then
        input_element2.Click
        Exit For
    End If
Next input_element2

编辑:好的,我已经测试了代码,并且可以正常工作。但是,我确实必须确保选中了两个引用:“ Microsoft HTML对象库”和“ Microsoft Internet控件”。

答案 1 :(得分:0)

有两种方法可以引用您感兴趣的元素:

'Targeted (if you know exactly at which order the elements appear in the list)
Dim li As HTMLListElement
Set li = IeDoc2.getElementById("accordion-leftmenu")    'get the list item you're interested in...
Debug.Print li.Children(1).innerText                    '...and access its sub-element in a targeted way
Debug.Print li.getElementsByTagName("a")(1).innerText   '...or find all <a></a> elements contained in it and access the one you're interested in, in a targeted way

'Non targeted (you have to search for it)
Dim element As HTMLObjectElement
For Each element In IeDoc2.getElementsByTagName("a")    'loop through all <a></a> elements...
    If element.innerText = "Advanced Search" Then       '...and find the one you're interested in
        Debug.Print element.innerText
    End If
Next element

出于演示目的,以上代码仅打印元素的内部文本。您可以对其进行相应的修改。

使用的参考:Microsoft HTML Object Library

此外,请在下一次发布实际的HTML而不是其屏幕截图。这样可以使人们更轻松地为您提供帮助。

相关问题