首页 > 解决方案 > VBA IE 如何使用 MouseEvetns 'mouseover' 和 'mouseleave' 单击按钮

问题描述

我在使用需要click操作的元素使网站自动化时遇到了挑战。这些元素的示例是搜索图标、链接和按钮。当我检查这些元素时,与这些元素类似的一件事是它们有一个 EventListener 'mouseenter' 和 'mouseover',而且我注意到它们有一个属性hidefocus="on"unselectable="on"我认为这是一个阻止我控制这些元素的属性。下面是用于按钮登录的示例源代码,主要元素是<a>并且事件附加到它,并且有一个<span>没有事件侦听器的子元素。

<a tabindex="0" class="x-btn-default-small" id="button-1028" role="button" aria-disabled="false" aria-hidden="false" hidefocus="on" unselectable="on" data-componentid="button-2018" data-qtip="Login">

<span class="x-btn-icon" id="button-1028-btnIconEl" role="presentation" data-ref="btnIconEl" unselectable="on" qa="btnIcon-loginButton">Login<span>

这个id按钮的 是动态变化的,所以我不能依赖那个属性,所以我改用这个innerText属性。以下是我已经尝试过但不起作用的代码。

Dim hrf As HTMLAnchorElement

'1st
For Each hrf In ie.document.getElementsByTagName("a")
    If hrf.innerText = "Login" Then
        hrf.Click: Exit For
    End If
Next hrf

'2nd
For Each hrf In ie.document.getElementsByTagName("a")
    If hrf.innerText = "Login" Then
        hrf.FireEvent "onmouseover"
        hrf.FireEvent "onmousedown"
        hrf.FireEvent "onmouseup"
        Exit For
    End If
Next hrf

'3rd
For Each hrf In ie.document.getElementsByTagName("a")
    If hrf.innerText = "Login" Then
        hrf.FireEvent "onclick"
        hrf.FireEvent "onmouseenter"
        hrf.FireEvent "onmouseleave"
        Exit For
    End If
Next hrf

'4th - dispatch event
Set evt = ie.document.createEvent("HTMLEvents") 'also tried "MouseEvents"
evt.initEvent "onclick", True, True 'also tried "onmouseenter", "mouseenter", "click", true, false/ false, false/false, true
For Each hrf In ie.document.getElementsByTagName("a")
    If hrf.innerText = "Login" Then
        hrf.dispatchEvent evt
        Exit For
    End If
Next hrf

我也尝试使用 span 元素,但仍然无法正常工作。希望您能够帮助我。

标签: htmlexcelvbaautomationwebautomation

解决方案


为什么不使用data-qtip属性及其值?显然,将其用作基础.FireEvent.dispatchEvent根据需要。无需循环。

ie.document.querySelector("[data-qtip=Login]").click

推荐阅读