[英]How to click on a <a> element of an <li> of a <ul> using 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在HTML中单击ul
的元素?
当我运行此代码时,什么也没有发生。 没有错误,但没有结果。
在左侧菜单的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控件”。
有两种方法可以引用您感兴趣的元素:
'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而不是其屏幕截图。 这样可以使人们更轻松地为您提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.