首页 > 解决方案 > 如何使用 VBA 单击基于 Java 的 Web 按钮?

问题描述

我试图使用 VBA 从以下网页中抓取数据:

https://www.kap.org.tr/tr/bildirim-sorgu

在搜索项目之前,我首先需要在下方的多选按钮中输入一些条件。这就是我的问题开始的地方。我正在尝试单击位于“通知类型”下的“所有通知”选项卡。但是有些我无法做到这一点。1

我试过以下代码:

Sub VBAWebScraping()

Dim IEObject As InternetExplorer

Set IEObject = New InternetExplorer


IEObject.Visible = True


IEObject.navigate Url:="https://www.kap.org.tr/tr/bildirim-sorgu"


Do While IEObject.Busy = True Or IEObject.readyState <> READYSTATE_COMPLETE
    
    Application.Wait Now + TimeValue("00:00:01")
    
Loop

Dim KAPMainPage As HTMLDocument
Set KAPMainPage = IEObject.document

Dim Filters As IHTMLElementCollection
Set Filters = KAPMainPage.getElementsByClassName("filter-multi padding right")

Dim NotiType As IHTMLElement
Set NotiType = Filters.Item(2)

NotiType.Click

Dim cbxItems2 As IHTMLElementCollection
Set cbxItems2 = KAPMainPage.getElementsByClassName("multiSelectItem vertical")


Dim NButton As Object
Set NButton = cbxItems2.Item(925)

NButton.Click

IEObject.Visible = False
End Sub

我是 VBA 和所有这些东西的初学者,我被困住了。如果有人可以帮助我,我将不胜感激。

提前致谢

标签: jqueryexcelvbaweb-scrapingclick

解决方案


您的代码中存在时间问题。你可以用一个循环来解决它。在那之后,我优化了代码,并从early binding切换到了late binding。这样就没有必要将绑定设置为HTML 对象库Internet 控件。但IntelliSense不适用于后期绑定。

代码中有一些注释供您参考:

Sub VBAWebScraping()

Const url As String = "https://www.kap.org.tr/tr/bildirim-sorgu"
Dim ie As Object
Dim nodeNotificationType As Object
Dim startTimeout As Double

  Set ie = CreateObject("InternetExplorer.Application")
  ie.Visible = True
  ie.navigate url
  'Wait for the right HTML element
  startTimeout = Timer
  Do
    'Switch off error handling
    On Error Resume Next
    'Try to catch the jQuery dropdown for the notification type
    Set nodeNotificationType = ie.document.getElementsByClassName("filter-multi padding right")(2)
    'Switch on error handling
    On Error GoTo 0
  'Try it again till the dropdown was loaded or until timeout
  Loop Until (Not nodeNotificationType Is Nothing) Or (Timer - startTimeout > 5) 'Timeout in seconds
  
  'Check wether the dropdown was loaded
  If Not nodeNotificationType Is Nothing Then
    'Click to open the dropdown
    nodeNotificationType.Click
    'Click on the first entry. That's the element with the index 0 in the node collection
    'The dropdown entries are in another element of the HTML document
    'Not in the object variable nodeNotificationType
    'It's the next HTML element in the same hierarchy level of the HTML document
    'Therefore it's the nextSibling
    nodeNotificationType.NextSibling.getElementsByClassName("multiSelectItem vertical")(0).Click
  Else
    'If nodeNotificationType is not available after timeout
    MsgBox "Page was not loaded till timeout takes effect."
  End If
End Sub

推荐阅读