[英]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. 我正在用excel编制一组不寻常的货币配对,我希望用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'. 我收到“运行时错误'91':对象变量或未设置块变量”。 I'm relatively new to VBA and i've put a lot a deal of thought into this. 我是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
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. 特别是,在您提供的屏幕截图中,我看不到divQuotePage
。
But if you want the quote (793.19) you could do something like: 但是,如果您想要报价(793.19),则可以执行以下操作:
Dim V As Variant
Set V = ie.document.getelementbyid("dtaLast")
TxtRng = V.innertext
This will work. 这将起作用。
Sub Test() Dim IE As Object 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
End Sub 结束子
You can target that element with a CSS selector of div.pricechangerow > span.last-change
; 您可以使用div.pricechangerow > span.last-change
的CSS选择器来定位该元素; which can be simplified to .last-change
. 可以简化为.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 那是网站当前版本的2018-06-30
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.