VBA 网页抓取:单击列表元素 [英] VBA web-scraping: click on element of a list

查看:47
本文介绍了VBA 网页抓取:单击列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个从网页自动下载历史股票数据的 vba 程序.我要选择的元素的相应 HTML 代码如下图所示:我想点击的元素的 HTML 代码

I would like to write a vba Programm which downloads automaticaly historical stock data from a web-page. The correspindent HTML-Code of the Element I would like to select is on the following Picture: HTML code of the element I would like to click on

我的 VBA 代码如下所示:

My VBA-code Looks as follows:

    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 对象保持为空.

But unfortunaly the object HTMLCurButton stays empty.

非常感谢您的帮助!

推荐答案

一个非常有趣的问题.我认为您无法使用 Internet Explorer 解决此问题.这是因为该列表位于受 同源策略 保护的 iframe 中,即您无法导航到包含您的列表的内部文档的 src.

A very interesting problem. I don't think you can solve this with Internet Explorer. This is because the list is in an iframe which is protected by a same origin policy i.e. you cannot navigate to the src of the inner document housing your list.

在 Chrome 中使用 selenium basic vba 可以切换到适当的 iframe.然后,您需要满足几个测试条件,以便有足够的时间让您在页面上的操作生效.

Using selenium basic vba with Chrome it is possible to switch to the appropriate iframe. You then need a couple of test conditions to be met that allow sufficient time for your actions on the page to take effect.

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

这篇关于VBA 网页抓取:单击列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆