Search code examples
vbaparsingdropdownframe

Webscraping: how to select a value (option) from a dropdown list on a webpage using VBA)


On a website I was able to log in and then I was trying to select a value from a dropdown menu but I can't get any object containing the menu.

On concern is that the page seem to be using three frame windows-the dropdown menu is on one of the windows.

<label for="edit-multiple-form">...</label>
<select id="edit-multiple-form" name="NNN" class="form-select form-control required ajax-processed"> == $0
   <option value selected="selected">- Select -</option>
   <option value="1"> OPTION1 </option>
   <option value="2"> OPTION2 </option>
   <option value="3"> OPTION3 </option>
</select>
::after
</div>

VBA codes (updated):

Sub LogIn()

' ' ' ' ' 

'when Error
On Error GoTo Err_Clear

' ' ' ' ' 

'New HTML Document for the page
Dim IE3 As HTMLDocument
Set IE3 = IEBrowser.document

Dim elemSelect As IHTMLElement
Dim elemOption As IHTMLElement

Set elmSelect = IE3.getElementById("edit-multiple-wallet-form")
    Debug.Print elemSelect.innerText        
Set elemOption = elemSelect.getElementByTagName("option")  '@@ it gives me an error
If elemOption.Length > 0 Then
    Dim i, text
    For i = 0 To elemOption.lengh - 1
        text = text & elemOption.Item(i).innerText
    Next
    MsgBox "All pre elements text: " & text
End If
 
    ' ' ' ' ' 


Err_Clear:
If Err <> 0 Then 
Err.Clear
Resume Next
End If

End Sub

====================================================================

 'Got a new HTML document after log on the the first page
    Dim IE3 As HTMLDocument
    Set IE3 = IEBrower.document
    
'then tried several methods to get the object using the following commands 
IE3.document.querySelector("option")

IE3.all.NNN.value   'NNN is the name of the dropdown menu object

IE3.getElementsByID("edit-multiple-form)

IE3.getElementsByClass("form-select form-control required ajaz-processed")

==========================================================================

I was able to grab the dropdown menu object but still got an error at @@ What is wrong with it? Any help would be appreciated.


Solution

  • IE3.getElementById("edit-multiple-form")
    

    This should return the select HTML element. Then you can further narrow by:

    Set elemSelect = IE3.getElementById("edit-multiple-form")
    Set elemOption = elemSelect.getElementsByTagName("option")
    

    So then you can loop through (for i=0 to elemOption.length-1). Please note that getElementById does not have s in it, because it always returns exactly 1 item. Also, getElementsByClass is not a valid method, use getElementsByClassName instead. The list of available methods are listed here