在 Internet Explorer 中自动点击(展开)加号

Automate click(expanding) plus signs within internet explorer

我正在致力于将一些数据自动输入到 Intranet 网页中。我过去曾成功使用这种类型的代码来单击复选框,但无法使其在扩展行的加号上工作。下面的代码什么都不做,也没有提示错误,代码正常运行。

这是我的代码:

Set div = IE.document.getElementsByTagName("div")

For Each i In div
    'showExpand?
    If i.id Like "iconShowA*" Then
        If i.onclick = "showExpand(*)" Then
            i.Click'Click plus sign
            v = Replace(i.id, "iconShowA", "")
            col.Add v 'store the numeric part
        End If
    End If
Next i

For Each v In col
    Debug.Print v
Next v

相关的 HTML 行是:

(我要点击的内容,可以有不同数量的具有不同数字标识符的这些 "iconShowA(x)")

<div id="iconShowA34" class="ui-icon ui-icon-plusthick" onclick="showExpand('34','34')" ;="" style="display: block;"></div>

(我也需要避免点击这些)

<div id="iconShowA_N4" class="ui-icon ui-icon-plusthick" onclick="showExpandSub('4','4')" ;=""></div>

下面的代码能够达到预期的效果。我无法使 TagName 约定起作用。此方法使用 getElementByID 在网页中导航。使用完整 ID 似乎至关重要,因此我使用 Do While 循环遍历 ID 命名约定中可能使用的数字。

n = DateDiff("ww", firstDate, secondDate)'Determines number of plus' to click
v = 0 'Counter for plus click event
x = 6 ' starting value for numerical piece of Id


Do While n > v 'continue loop until all plus' have been clicked
Set div = IE.document.getElementById("iconShowA" & x) 'Id must be defined completely to click
    If div Is Nothing Then 'tests if element exists
        x = x + 7
    Else
        div.Click 'clicks an element that exists
        v = v + 1
        x = x + 7 'iterates id number by 7 as that is convention of website
    End If
Loop

CSS select或:

假设您要单击的所有元素都有 showExpandSub 而不是 showExpand 那么您可以使用 CSS select 或者 select 这些元素:

div[onclick^='showExpand(']

这表示带有 div 标签的元素具有属性 onclick,其值以 'showExpand(' 开头。


CSS查询:


VBA:

使用document的querySelectorAll方法return一个所有匹配元素的nodeList。然后循环 .Length 以检索元素。

Dim aNodeList As Object, iNode As Long
Set aNodeList = ie.document.querySelectorAll("div[onclick^='showExpand(']")
For iNode = 0 To aNodeList.Length - 1
    Debug.Print aNodeList.item(iNode).innerText
    'Debug.Print aNodeList(iNode).innerText '<== Sometimes this syntax
Next iNode