【问题标题】:Webscraping: how to select a value (option) from a dropdown list on a webpage using VBA)Web Scraping:如何使用 VBA 从网页上的下拉列表中选择一个值(选项)
【发布时间】:2021-02-11 12:37:46
【问题描述】:

在一个网站上我能够登录,然后我试图从下拉菜单中选择一个值,但我无法获得包含该菜单的任何对象。

令人担忧的是该页面似乎正在使用三个框架窗口 - 下拉菜单位于其中一个窗口上。

<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 代码(更新):

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")

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

我能够抓取下拉菜单对象,但在 @@ 处仍然出现错误 它有什么问题? 任何帮助将不胜感激。

【问题讨论】:

    标签: vba parsing dropdown frame


    【解决方案1】:
    IE3.getElementById("edit-multiple-form")
    

    这应该返回 select HTML 元素。然后您可以通过以下方式进一步缩小范围:

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

    那么你可以循环遍历(对于 i=0 到 elemOption.length-1)。请注意,getElementById 中没有 s,因为它总是只返回 1 个项目。此外,getElementsByClass 不是有效方法,请改用 getElementsByClassName。 列出了可用方法列表here

    【讨论】:

    • 谢谢!!我能够抓住物体。但我仍然在 elemOption 遇到错误,所以我无法选择“OPTION1”你认为问题是什么?
    • 如果没有看到您尝试过的内容,很难说。下次请发布不起作用的代码。在监视窗口中检查 elemOption。它返回一组选项 HTML 元素,因此您必须选择要使用的元素。检查 elemOption(0) 那里,这应该是你的第一个元素。
    • 抱歉,elemOption(0) 将返回占位符项。使用 elemOption(1) 获得 OPTION1。或者,如果您想动态检查,请使用从 0 到 elemOption.length-1 的 for 循环并检查 elemOption(i).innerText
    猜你喜欢
    • 2017-06-01
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2018-09-26
    • 2018-04-24
    • 1970-01-01
    相关资源
    最近更新 更多