【问题标题】:Referencing 'onclick' event for If statement - IE automation为 If 语句引用“onclick”事件 - IE 自动化
【发布时间】:2020-01-23 21:01:18
【问题描述】:

抱歉,如果这有点令人困惑。但是,我在这里有点超出我的深度。我有一个自动化 IE 的宏。有一次,我的宏导航到用于下载报告的 URL。 URL 几乎总是相同的。但是,链接中的一位数字有时会发生变化。链接中发生变化的数字只能是12。获取报告按钮的onclick 事件指示将生成哪个报告。因此,我需要我的宏有一个IF 语句来读取onclick,如果onclick1,那么它将导航到带有1 的链接或者如果它是@ 987654329@,它将导航到带有2 的链接。我在下面提供了onclick 的详细信息:

Link with 'ReporttypeID=1'

<input name="btnContinue" class="primary" id="btnContinue" onclick="javascript:pop('Splash.aspx?SplashID=3&amp;../Reports/ReportView.aspx&amp;ReporttypeID=1&amp;lang=EN&amp;ruletypeid=5&amp;ruleid=0'); return false;" type="submit" value="Continue">```

Link with 'ReporttypeID=2'

<input name="btnContinue" class="primary" id="btnContinue" onclick="javascript:pop('Splash.aspx?SplashID=3&amp;../Reports/ReportView.aspx&amp;ReporttypeID=2&amp;lang=EN&amp;ruletypeid=5&amp;ruleid=0'); return false;" type="submit" value="Continue">```

我的代码如下,如何调用/引用 onclick id?

Sub login()
    Application.DisplayAlerts = False
    Dim url As String
    url = UserForm.Path2.Value

    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")

    With ie 'Open IE
        .navigate url
        ieBusy ie
        .Visible = False

        ie.navigate "https://mylink.com/ReporttypeID=1" 'Currently navigate to this set link
    'Need IF statement to say if onclick = 1 then go to above link, else if it = 2 then go to the below link
        'ie.navigate "https://mylink.com/ReporttypeID=2"

        ieBusy ie

    End With 'End IE actions

    Application.DisplayAlerts = True
End Sub

【问题讨论】:

    标签: excel vba internet-explorer automation onclick


    【解决方案1】:

    这些答案基于始终存在一个或另一个。

    提取onclick属性,测试是否包含字符串"ReporttypeID=1"

    If Instr(ie.document.getElementById("btnContinue").getAttribute("onclick"),"ReporttypeID=1")> 0 Then
        'report 1
    Else
      'report 2
    End If
    

    另一种方法是使用带有包含运算符的 css attribute = value selector 来检查 nodeList 长度

    If ie.document.querySelectorAll("[onclick*='ReporttypeID=1']").Length > 0 Then
        'report 1
    Else
      'report 2
    End If
    

    【讨论】:

    • 谢谢,我无法让第一个解决方案正常工作,因为我不断收到未定义对象的调试错误,不确定我的代码中是否可能缺少某些内容,但第二个解决方案运行良好。谢谢! IE 自动化有点超出我的深度,我最近才学会如何通过查找 ID 来操作页面,你能详细说明 css 属性的作用和工作原理吗?
    • 这里有一个很好的解释:developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors 我们通过 HTMLDocument (ie.document) 的 querySelector 或 querySelectorAll 方法应用 css 选择器,这将返回第一个匹配作为节点,或所有匹配作为 nodeList (分别)。 nodeList 有一个 .Length 属性,它告诉您为 css 选择器检索了多少个节点。
    猜你喜欢
    • 2014-05-31
    • 2020-12-23
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多