VBA抓取网络:单击列表元素

时间:2019-03-03 14:34:28

标签: html vba web-scraping

我想编写一个vba程序,该程序可以从网页上自动下载历史库存数据。 我要选择的元素的相应HTML代码在下面的图片上: HTML code of the element I would like to click on

我的VBA代码如下:

    Dim IE As SHDocVw.InternetExplorer
  Dim HTMLDoc As mshtml.HTMLDocument
  Dim HTMLCurButton As mshtml.IHTMLElement

  Set IE = New SHDocVw.InternetExplorer

  IE.Visible = True
  IE.FullScreen = False
  IE.Resizable = True
  IE.Navigate "https://www.dukascopy.com/swiss/english/marketwatch/historical/"

  Do While IE.ReadyState <> READYSTATE_COMPLETE
  Loop

  Set HTMLDoc = IE.Document
  Set HTMLCurButton = HTMLDoc.getElementById(":6n")
  HTMLCurButton.Click

但是不幸的是,对象HTMLCurButton保持为空。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

一个非常有趣的问题。我认为您无法使用Internet Explorer解决此问题。这是因为列表位于受same origin policy保护的iframe中,即您无法导航到容纳列表的内部文档的src。

在Chrome中使用硒基本vba可以切换到适当的iframe。然后,您需要满足一些测试条件,以便有足够的时间使页面上的操作生效。

Option Explicit
Public Sub MakeChanges()
    'VBE > Tools > References > Selenium Type Library
    'Download: https://github.com/florentbr/SeleniumBasic/releases/tag/v2.0.9.0
    Dim d As WebDriver, t As Date
    Set d = New ChromeDriver
    Const url = "https://www.dukascopy.com/swiss/english/marketwatch/historical/"

    With d
        .Start "Chrome"
        .get url
        .SwitchToFrame .FindElementByCss("script + iframe")
        t = Timer
        Do
            With .FindElementByCss("[data-instrument='A.US/USD']")
                .Click
                If .Attribute("aria-selected") Then Exit Do
            End With
        Loop While Timer - t < 10
        With .FindElementByCss(".d-wh-vg-v-p > div")
            If Not .Attribute("aria-disabled") Then .Click
        End With
        'other code now presented with accept and then login details
        Stop
        .Quit
    End With
End Sub