Search code examples
vbainternet-explorer

Select button by looping through all innerHTML


I am trying to get all the buttons using queryselector and select the particular button by looping through and finding innerHTML.

After finding the particular button, when click event is passed, nothing happens.

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "https://www.spirit.com/"
Do Until IE.readyState = 4: Application.Cursor = xlDefault: DoEvents: Loop

Application.Wait (Now + TimeValue("00:00:03"))
IE.document.querySelector("label[for='radio-oneWay']").Click

Application.Wait (Now + TimeValue("00:00:03"))
IE.document.querySelector("input[id='flight-OriginStationCode']").Click
Set elems = IE.document.getElementsByTagName("button")

For Each elem In elems
    If (elem.innerHTML) = " Aguadilla, Puerto Rico (BQN) " Then
        elem.Click
        Exit For
    End If
Next elem

Solution

  • The two airport boxes can be assigned by simulating input using SendKeys then the click event will be triggered. The date-input and other textbox will be set separately. Here is the code which implements this function:

    Private Sub CommandButton1_Click()
    
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    IE.Navigate "https://www.spirit.com/"
    Do Until IE.readyState = 4: Application.Cursor = xlDefault: DoEvents: Loop
    
    Application.Wait (Now + TimeValue("00:00:03"))
    IE.document.querySelector("label[for='radio-oneWay']").Click
    
    Application.Wait (Now + TimeValue("00:00:03"))
    
    Set elems = IE.document.getElementsByTagName("button")
    
    Set txt1 = IE.document.getElementsByName("originStationCode")(0)
    txt1.Focus
    SendKeys ("BQN")
    Application.Wait (Now + TimeValue("00:00:01"))
    
    Set txt2 = IE.document.querySelector("input[id='flight-DestinationStationCode']")
    txt2.Focus
    SendKeys ("BDL")
    Application.Wait (Now + TimeValue("00:00:01"))
    
    Application.Wait (Now + TimeValue("00:00:01"))
    IE.document.querySelector("input[id='flight-Date']").Value = "2020/10/09-2020/10/19"
    IE.document.querySelector("input[id='promoCode']").Value = "xx"
          
    IE.document.querySelector("button[type='submit']").Click
    End Sub
    

    Result:

    enter image description here