簡體   English   中英

從HTML表中抓取單個值,然后使用VBA插入Excel單元格

[英]Scraping a single value from an HTML table and inserting into an Excel cell with VBA

請參見下面的代碼。 我正在用excel編制一組不尋常的貨幣配對,我希望用VBA抓取此數據。 我只想將值本身插入單元格中。 有人知道我在哪里錯嗎? 我收到“運行時錯誤'91':對象變量或未設置塊變量”。 我是VBA的新手,對此我投入了很多思考。

Sub ie_open()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim TxtRng As Range
    Dim ie As Object

    Set ie = CreateObject("INTERNETEXPLORER.APPLICATION")
    ie.NAVIGATE "http://www.barchart.com/quotes/forex/British_Pound/Costa_Rican_Colon/%5EGBPCRC"
    ie.Visible = True

    While ie.ReadyState <> 4
        DoEvents
    Wend

    Set wb = ActiveWorkbook
    Set ws = wb.Sheets("Test Sheet")
    Set TxtRng = ws.Range("A1")
    TxtRng.Value = ie.document.getelementsbyname("divQuotePage").Item.innertext

End Sub

這是我要抓取的數據:

謝謝。

我在網絡抓取方面還沒有做到這一點,但是這種錯誤通常意味着您所尋找的東西不存在。 特別是,在您提供的屏幕截圖中,我看不到divQuotePage

但是,如果您想要報價(793.19),則可以執行以下操作:

Dim V As Variant
Set V = ie.document.getelementbyid("dtaLast")
TxtRng = V.innertext

這將起作用。

Sub Test()Dim IE作為對象

Set IE = CreateObject("InternetExplorer.Application")
With IE
    .Visible = True
    .Navigate "http://www.barchart.com/quotes/forex/British_Pound/Costa_Rican_Colon/%5EGBPCRC" ' should work for any URL
    Do Until .ReadyState = 4: DoEvents: Loop

        x = .document.body.innertext
        y = InStr(1, x, "Last Price")
        Z = Mid(x, y, 19)

        Range("A1").Value = Trim(Z)

        .Quit
    End With

結束子

您可以使用div.pricechangerow > span.last-change的CSS選擇器來定位該元素; 可以簡化為.last-change

“。” 表示類別,您可以使用

Debug.Print ie.document.querySelector.querySelector(".last-change").innerText

那是網站當前版本的2018-06-30

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM