【问题标题】:VBA select drop down menu value from HKEX websiteVBA 从 HKEX 网站选择下拉菜单值
【发布时间】:2022-01-13 03:49:49
【问题描述】:

我正在尝试从以下网站抓取表格。网站左侧有一个下拉列表,我想选择并单击类型部分中的“专业”。下面是我的 VBA 代码。我没有网络开发经验,我只能找到我想要的表格并选择显示 100 个项目

Sub CopyFromHKEXWebsite()
    Dim ie As Object, btnmore As Object, tbl As Object
    Dim cnt As Integer
         
    Set ie = CreateObject("internetexplorer.application")
    
    With ie
        .Visible = True
        .navigate "https://www.hkex.com.hk/Market-Data/Securities-Prices/Debt-Securities?sc_lang=en"
        
        Do
            DoEvents
        Loop While .ReadyState <> 4 Or .Busy
        
        .Document.getelementsbyclassname("select_items")(0).setAttribute "style", "display: block"
            Do
                DoEvents
            Loop While .Busy  'wait for scriptcode to execute
        .Document.getelementsbyclassname("select_items")(0).Children(2).Click
        
        Do
            DoEvents
        Loop While .ReadyState <> 4 Or .Busy
        
        ****'professional
        .Document.getelementsbyid("select2")(0).selectedindex = 1
            Do
                DoEvents
            Loop While .Busy  'wait for scriptcode to execute****
                     
        Do
            Set tbl = .Document.getelementsbyclassname("table_debtsecurities")(0)
            Set btnmore = .Document.getelementsbyclassname("loadmore")(0)
            cnt = cnt + 1
            Application.Wait Now + TimeValue("00:00:01")
            
        Loop While tbl Is Nothing Or btnmore Is Nothing And cnt < 5 'maximum attempts = 4
        
        Do While btnmore.getattribute("style") = ""
            btnmore.Click
            Do
                DoEvents
            Loop While .Busy
        Loop
    
    End With
    
End Sub

【问题讨论】:

  • 这个问题有一个捷径,只要把网站改成https://www.hkex.com.hk/Market-Data/Securities-Prices/Debt-Securities?sc_lang=en&amp;type=0(在“sc_lang=en”后面加“&type=0”)然后网站会自动转换成“专业”表,但我想了解更多使用 VBA 的工作原理.click 函数

标签: html excel vba web-scraping


【解决方案1】:

首先它不是GetElementsById,而是GetElementById(单数Element,没有s),因为不能有多个元素具有相同的ID(不违反HTML标准)。而对于 NameClassName 可以存在多个元素,它需要是复数 Elementss

第二个你通过name="select2"找到组合框,所以我们需要使用GetElementsByName

<input type="hidden" name="select2" value="ALL">
Dim TypeCombo As Object
Set TypeCombo = .document.GetElementsByName("select2")(0)
TypeCombo.Value = "Professional"

然后是应用按钮

<div class="etps_apply_btn">APPLY FILTERS</div>

可以通过它的class="etps_apply_btn"找到,所以我们使用GetElementsByClassName

Dim ApplyButton As Object
Set ApplyButton = .document.GetElementsByClassName("etps_apply_btn")(0)
    
ApplyButton.Click

并应用点击。

【讨论】:

  • 谢谢!代码运行顺利,完全符合我的意图!非常感激!顺便说一句,如果我想了解更多关于 html 或使用 vba 抓取数据的信息,你有什么资源推荐吗? :)
  • StackOverflow web-scraping 包括 vba
猜你喜欢
  • 2017-05-10
  • 2012-10-01
  • 2023-04-03
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多