我正在尝试用 Excel VBA从网页中抓取一些数据。
HTML代码是:
eks mva
kr
151,20
/
RL
我想要抓取的东西是value的值,位于第一个"span"。
我尝试过: .document.getElementById("skuPriceLabel").getElementsByTagName("span")(0).innerText
这有时会给出值"eks mva",而在其他时候运行时错误 424 ( 需要对象) 。
我尝试使用 .document.getElementById("skuPriceLabel").getElementsByTagName("span")(1).innerText 和 .document.getElementById("skuPriceLabel").getElementsByTagName("span")(2).innerText 同样,但这些错误给了 424运行时错误。
请告诉我如何阅读html代码,以便我能看到逻辑,知道下次查找和写作的内容。
我的完整代码是Sub get_data_2()
'Source for this code is:
'http://stackoverflow.com/questions/26613043/get-data-out-of-a-webpage-with-vba
Dim ie As Object
Dim sht As Worksheet
Dim SKU As String
Dim RowCount As Long
Set sht = Sheet8
Set ie = CreateObject("InternetExplorer.application")
RowCount = 1
'This just gives the columns a titel i row numer 1.
sht.Range("a" & RowCount) ="SKU" 'Column A is populated with SKU's to be looked up.
sht.Range("n" & RowCount) ="Price" 'Column N will be given the price of the SKU.
With ie
. Visible = True
. navigate"http://www.staples.no/"
Do While. Busy Or _
. readyState <> 4
DoEvents
Loop
Do
RowCount = RowCount + 1
SKU = sht.Range("a" & RowCount).Value
With ie 'fill in the searchbox and submit.
ie.document.all("searchKeywords").Value = SKU 'we can use 491215 as a SKU for this example.
ie.document.forms("searchForm").submit
Do While. Busy Or _
. readyState <> 4
DoEvents
Loop
'write the price to column N
sht.Range("n" & RowCount).Value = ie.document.getElementById("skuPriceLabel").getElementsByTagName("span")(1).getElementsByTagName("span")(0).innerText
End With
Loop While sht.Range("a" & RowCount + 1).Value <>"" 'Loop as long as column A has a SKU (till end of list).
End With
Set ie = Nothing
End Sub