You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求编写VBA代码:网页Proforma标签可见时点击,不可见则跳过

问题描述

我尝试用以下VBA代码点击网页中的标签:

Set P = D.FindElementByCss("a[href='#pro-content-pro']")
P.Click

这段代码在标签可见时能正常运行,但标签不可见时无法生效。以下是标签两种状态下的HTML代码:

可见状态HTML

<li data-bind="attr:{ 'id': id }, click: onClick, visible: isVisible, css: {'active': isActive, 'disabled-control': !isEnabled() }" class="active">
                <a data-toggle="tab" role="tab" data-bind="attr:{ href: '#' + sectionId, id: linkId }, css: { 'disabled': !isEnabled() }" href="#pro-content-pro">
                    <span data-bind="text: title">Proforma</span>
                </a>
            </li>

不可见状态HTML

<li data-bind="attr:{ 'id': id }, click: onClick, visible: isVisible, css: {'active': isActive, 'disabled-control': !isEnabled() }" class="disabled-control">
                <a data-toggle="tab" role="tab" data-bind="attr:{ href: '#' + sectionId, id: linkId }, css: { 'disabled': !isEnabled() }" href="#pro-content-pro" class="disabled">
                    <span data-bind="text: title">Proforma</span>
                </a>
            </li>

需要实现标签不可见时跳过,可见时点击的逻辑。


解决方案

根据HTML结构的差异,我们可以通过检查元素的类属性或可见性状态来实现需求,以下是两种可靠的实现方式:

方法1:通过父元素类判断状态

观察可见/不可见状态下父li的class差异(可见时为active,不可见时为disabled-control),结合子元素的disabled类判断:

Dim parentLi As Object
' 捕获元素不存在的错误,避免代码中断
On Error Resume Next
Set parentLi = D.FindElementByCss("li:has(a[href='#pro-content-pro'])")
On Error GoTo 0

If Not parentLi Is Nothing Then
    Dim targetLink As Object
    Set targetLink = parentLi.FindElementByTag("a")
    
    ' 确认父元素未被禁用,且链接本身未标记为disabled
    If InStr(parentLi.Attribute("class"), "disabled-control") = 0 And _
       InStr(targetLink.Attribute("class"), "disabled") = 0 Then
        targetLink.Click
    End If
End If

方法2:直接检查元素可见性

利用IE自动化对象的IsVisible属性直接判断元素是否可见,同时验证链接的禁用状态:

Dim targetLink As Object
On Error Resume Next
Set targetLink = D.FindElementByCss("a[href='#pro-content-pro']")
On Error GoTo 0

If Not targetLink Is Nothing Then
    ' 元素可见且未被禁用时执行点击
    If targetLink.IsVisible And InStr(targetLink.Attribute("class"), "disabled") = 0 Then
        targetLink.Click
    End If
End If

关键说明

  • 使用On Error Resume Next是为了处理元素不存在的场景,避免代码抛出运行时错误中断流程。
  • 两种方法都先确认元素存在,再检查状态,确保符合“不可见/禁用时跳过,正常状态点击”的需求。

内容的提问来源于stack exchange,提问作者TCritical

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 15:58:11