如何获得针对具有不同网址的不同单元格进行网络抓取的结果?

时间:2019-07-03 19:29:21

标签: html excel vba

我正在建立一个电子表格,该电子表格每天都会从blackrock网站获取特定指数基金的资产净值。但是,这些指数基金有很多,并且每个单元的URL都会更改。我不确定如何继续制作的电子表格表格,并将目标值放在另一个单元格中。

我尝试依次列出每个可能的URL,但似乎可以正常工作,但是,我一直收到运行时错误,因此我必须假定有一种更有效的方法。

Sub GetCurrentPrices()
    Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
    Dim text As String

    With CreateObject("internetexplorer.application")
        .navigate "https://www.blackrock.com/uk/individual/products/xxxxxx/"
        Do While .Busy And .readyState <> 4: DoEvents: Loop
        text = .document.getElementsByClassName("header-nav-data")(0).innerText
        .Quit
    End With

    ws.Cells(32, 1).Value = text

    With CreateObject("internetexplorer.application")
        .navigate "https://www.blackrock.com/uk/individual/products/yyyyyy/"
        Do While .Busy And .readyState <> 4: DoEvents: Loop
        text = .document.getElementsByClassName("header-nav-data")(0).innerText
        .Quit
    End With

    ws.Cells(33, 1).Value = text

End Sub

当前,对于每个不同的URL,此代码被复制约22次。我也尝试过这样的事情:

Sub GetCurrentPrices2()
    Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
    Dim text As String
    Dim i As Integer
    i=32

    With CreateObject("internetexplorer.application")
        .navigate "https://www.blackrock.com/uk/individual/products/" & (ws.Range("H2:H24").Value) & "/"
        Do While .Busy And .readyState <> 4: DoEvents: Loop
        text = .document.getElementsByClassName("header-nav-data")(0).innerText
        .Quit
    End With

    Do Until i > 46
        ws.Cells(i,1).Value = text
    Loop

End Sub

1 个答案:

答案 0 :(得分:0)

假设A列包含感兴趣的指数基金,并且数据从第2行开始,则您的代码可以按如下方式重写...

Sub GetCurrentPrices()

    Dim ws As Worksheet
    Dim text As String
    Dim lastRow As Long
    Dim i As Long

    Set ws = ThisWorkbook.Worksheets("Sheet1")

    With ws
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    With CreateObject("InternetExplorer.Application")
        For i = 2 To lastRow
            .navigate "https://www.blackrock.com/uk/individual/products/" & ws.Cells(i, 1).Value & "/"
            Do While .Busy And .readyState <> 4: DoEvents: Loop
            text = .document.getElementsByClassName("header-nav-data")(0).innerText
            ws.Cells(i, 2).Value = text
        Next i
        .Quit
    End With

    Set ws = Nothing

End Sub