简体   繁体   中英

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

Please see the code below. I am compiling a list of unusual currency pairings in excel and I wish to scrape this data with VBA. I only want to insert the value itself into the cell. Does anyone know where I am going wrong here? I am getting a 'Run-time error '91': object variable or With block variable not set'. I'm relatively new to VBA and i've put a lot a deal of thought into this.

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

This is the data which I am trying to scrape:

Thanks.

I'm not that accomplished at web scraping, but that kind of error often means that what you are looking for isn't there. In particular, I don't see divQuotePage in the screen shot you provided.

But if you want the quote (793.19) you could do something like:

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

This will work.

Sub Test() Dim IE As Object

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

End Sub

You can target that element with a CSS selector of div.pricechangerow > span.last-change ; which can be simplified to .last-change .

The "." means class and you can retrieve this specific item with

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

That is for the website's current incarnation at 2018-06-30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM