【问题标题】:VBA Scraping Data From Multiple WebsitesVBA 从多个网站抓取数据
【发布时间】:2016-06-09 19:44:59
【问题描述】:

我正在尝试使用 VBA 从investing.com 上的多个页面中抓取商品/股票价格,并将它们插入到Excel 电子表格中。

以下代码是我正在努力做的单一价格,在这个例子中是黄金:

Sub Extractdatafromwebsite()

Dim ie As New InternetExplorer
Dim doc As HTMLDocument

ie.Visible = False
ie.navigate "http://uk.investing.com/commodities/gold"

Do
    DoEvents
    Loop Until ie.READYSTATE = READYSTATE_COMPLETE

Set doc = ie.document

output = doc.GetElementById("last_last").innerText
Range("A1").Value = output

ie.Quit

End Sub

但是,我需要来自多个网站的数据才能同时获得不同的价格。

我尝试详细说明我正在运行的代码,以下示例是我尝试显示黄金和白银价格的示例,但它仅在单元格 A1 和 A2 中显示黄金价格:

Sub Extractdatafromwebsite()

Dim ie As New InternetExplorer
Dim doc As HTMLDocument

ie.Visible = False
ie.navigate "http://uk.investing.com/commodities/gold"

Do
    DoEvents
    Loop Until ie.READYSTATE = READYSTATE_COMPLETE

Set doc = ie.document

output = doc.GetElementById("last_last").innerText
Range("A1").Value = output

ie.Quit

ie.navigate "http://uk.investing.com/commodities/silver"

Set doc = ie.document

output = doc.GetElementById("last_last").innerText
Range("A2").Value = output

ie.Quit


End Sub

请有人帮我弄清楚如何让它适用于多个页面?我试过搜索,但没有找到适合我需要的东西。

在收集数据的同时,是否可以弹出类似“Waiting...”之类的内容?

谢谢

【问题讨论】:

  • 首先,您可能不应该在第二个 Navigate 之前 Quit ie 实例,其次,您可能需要重复 Do..Loop Until 以让浏览器有时间完成正在加载页面...
  • 谢谢,工作得很好,我最初确实有循环,但它没有工作,删除了退出 ie 并对其进行了排序。再次感谢。

标签: excel vba


【解决方案1】:

我发现使用 READYSTATE 并不可靠,因为有时文档没有完全加载——或者至少对象模型没有加载。

所以我通常会在尝试访问新的 doc 对象之前添加一个睡眠命令和 Doevents

这应该对你有用(正如@Dave 所说,你不需要使用IE.Quit

Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

    Sub Extractdatafromwebsite()

        Dim ie As New InternetExplorer
        Dim doc As HTMLDocument        

        ie.Visible = False
        ie.Navigate "http://uk.investing.com/commodities/gold"
        Do
            Sleep 500
            DoEvents
        Loop Until ie.ReadyState = 4 ' READYSTATE_COMPLETE
        Sleep 500

        Set doc = ie.Document

        output = doc.GetElementById("last_last").innerText
        Range("A1").Value = output

        ie.Navigate "http://uk.investing.com/commodities/silver"

        Do
            Sleep 500
            DoEvents
        Loop Until ie.ReadyState = 4 ' READYSTATE_COMPLETE
        Sleep 500

        Set doc = ie.Document

        output = doc.GetElementById("last_last").innerText
        Range("A2").Value = output

        ie.Quit
        Set ie = Nothing

    End Sub

【讨论】:

  • 您可以将Range("A1").Value = outputRange("A2").Value = output 命令添加回
  • 在代码顶部添加了 Win32 API 睡眠功能,以防万一你没有那个方便。确保将它放在模块的最顶部,高于所有常量和子例程。让我知道这是否对你有用。
猜你喜欢
  • 2015-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 2021-01-23
  • 2014-07-06
相关资源
最近更新 更多