James Knight
James Knight

Reputation: 13

VBA, search HTML ElementIDs for text string

During a web data scrape I have the following line which works:

IE.document.GetElementById("ct175_tocAccept").Click

The problem is that the company frequently updates their site at inconsistent intervals and changes the above ct# every time. Personally, I don't mind updating it frequently, but realistically that's not an option since I have coworkers who often need these results immediately and are unable to resolve the problem on their own.

Is there a way for me to search all ElementIds on that site for the text "tocAccept" and then click that result? The item does not have a name for me use as an alternative. All suggestions and solutions are greatly appreciated.

Edit: Source:

<div class="checkbox">
            <label for="ctl00_ctl76_g_22c8fb90_9788_4417_b231_10df683e9930_ctl00_tocAccept" class="required" aria-required="true">
                <input name="ctl00$ctl76$g_22c8fb90_9788_4417_b231_10df683e9930$ctl00$tocAccept" type="checkbox" id="ctl00_ctl76_g_22c8fb90_9788_4417_b231_10df683e9930_ctl00_tocAccept" aria-required="true" hasvalidation="true" data-rule-required="true" data-msg-required="Yes, I have read, understand and agree to these terms and conditions is required.">
                Yes, I have read, understand and agree to these terms and conditions</label>
        </div>

The major problem I'm having is that almost every elementid and name on the page uses the ct175 (now updated to ct176) portion. Also, to clarify, I said in the original post that the element does not have a name. The source code I provided does have a name, but there are multiple others that I need to work with that do not have one.

Upvotes: 1

Views: 2379

Answers (1)

K.Dᴀᴠɪs
K.Dᴀᴠɪs

Reputation: 10139

Obviously was unable to test this without having the site in front of me, but you have two objects you can iterate through, and click the one that meets all criteria, which appears to:

  • Have a parent class of checkbox
  • Has a tagname of label

Code:

Option Explicit

Sub TEST()

    ' Code Above

    Dim objCheckbox As Object, objCheckboxes As Object
    Dim objLabel As Object, objLabels As Object
    Set objCheckboxes = ie.document.getElementsByClassName("checkbox")

    For Each objCheckbox In objCheckboxes
        Set objLabels = Nothing
        On Error Resume Next
        Set objLabels = objCheckbox.getElementsByTagName("label")
        On Error GoTo 0
        For Each objLabel In objLabels
            If objLabel.innerText Like "*Yes, I have read, understand and agree*" Then
                objLabel.Click
                Exit For
            End If
        Next objLabel
    Next objCheckbox

End Sub

Upvotes: 2

Related Questions