VBA从多个网站上刮取数据

我正在尝试使用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 

请有人可以帮我弄清楚如何让这个工作多个页面? 我试过search,但没有拿出任何适合我的需求。

在收集数据的同时,还有可能会popup一些类似“Waiting ….”的内容。

谢谢

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

所以我通常在尝试访问新的doc对象之前添加一个sleep命令和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