【问题标题】:Vba- retrieve value from multiple internet explorer websites to multiple cellsVba-从多个 Internet Explorer 网站检索值到多个单元格
【发布时间】:2014-11-12 16:59:54
【问题描述】:

问题:

我想从多个 Internet Explorer 网站检索特定值(Prev Close)并将它们自动复制到多个单元格(C 列)。我知道如何将价值从单个 Internet Explorer 网站检索到单个单元格。但我不知道如何从多个网站检索并将它们复制到多个单元格。

我的电脑信息:

1.window 8.1

2.excel 2013

3.ie 11

我的 Excel 参考资料

微软对象库:是的

Microsoft Internet Controls:是的

Microsoft Form 2.0 对象库:是

Microsoft Script Control 1.0:是的

网址:

http://finance.yahoo.com/q?s=hpq&type=2button&fr=uh3_finance_web_gs_ctrl1&uhb=uhb2

下面是我的 VBA 代码:

Private Sub CommandButton1_Click()

Dim ie As Object
Dim Doc As HTMLDocument
Dim prevClose As String


Set ie = CreateObject("InternetExplorer.Application")

    ie.Visible = 0

    ie.navigate "http://finance.yahoo.com/q;_ylt=AsqtxVZ0vjCPfBnINCrCWlXJgfME?uhb=uhb2&fr=uh3_finance_vert_gs_ctrl1_e&type=2button&s=" & Range("b2").Value
    Do
    DoEvents
    Loop Until ie.readyState = 4



Set Doc = ie.document


prevClose = Trim(Doc.getElementById("table1").getElementsByTagName("td")(0).innerText)
Range("c2").Value = prevClose


End Sub

【问题讨论】:

  • 您需要使用多个标签,还是只是从多个网站获取?
  • @ptwales 多个网站都可以

标签: vba internet-explorer web-scraping pull yahoo-finance


【解决方案1】:

除非确实需要,否则不要使用多个选项卡。这是一个不可扩展的解决方案,随着标签的增加而迅速中断。

使用简单的循环结构一次只使用一个选项卡并处理一个网页要简单得多。为此,我假设您的网址是您提供的网址 + 列 B 中包含的一些字符串。

Private Sub CommandButton1_Click()
    Const YAHOO_PARTIAL_URL As String = "http://finance.yahoo.com/q;_ylt=AsqtxVZ0vjCPfBnINCrCWlXJgfME?uhb=uhb2&fr=uh3_finance_vert_gs_ctrl1_e&type=2button&s="

    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = 0

    For r = 2 To 10 ' Or whatever your row count is.
        ie.navigate YAHOO_PARTIAL_URL & Cells(r, "B").Value
        Do
            DoEvents
        Loop Until ie.readyState = 4

        Dim Doc As HTMLDocument
        Set Doc = ie.document

        Dim prevClose As String
        prevClose = Trim(Doc.getElementById("table1").getElementsByTagName("td")(0).innerText)
        Cells(r, "C").Value = prevClose
    Next r

End Sub

【讨论】:

  • 我试过你的代码。它有时能够检索 1 行。有时 2 行,甚至 3 行。然后它会显示运行时错误91。然后我调试它。它发生在这行代码上:prevClose = Trim(Doc.getElementById("table1").getElementsByTagName("td")(0).innerText)
  • 这意味着当代码试图访问它时该元素不存在。有两种可能性。 1) 该元素在该网页上不存在或 2) 代码在加载之前尝试访问它。我 99% 是后者。
  • @pexpex223 请参阅 this answer 等待元素加载后再访问它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多