【发布时间】:2019-02-10 08:56:42
【问题描述】:
我正在尝试使用 Excel VBA 从网页中获取产品价格。以下代码在使用 VBA Internet Explorer 导航请求时有效。但是,我想使用 XML HTTP 请求来加快抓取过程。
在 IE 请求代码中,我告诉应用程序等待 3 秒以使页面完全加载并能够抓取产品价格。如果不包括此行,它将找不到价格。
我尝试使用 XML HTTP 请求(参见第二个代码)来更改它,但没有成功。没有找到价格输出。似乎代码试图在页面完全加载之前抓取页面。
如何调整 XML HTTP 请求代码,以便它可以找到产品价格(并且仅在页面(和脚本)完全加载时才开始搜索/抓取?
以下 IE 请求代码正在运行: (立即调试。打印产品价格)
Sub Get_Product_Price_AH_IE()
Dim IE As New SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument
Dim AHArticles As MSHTML.IHTMLElementCollection
Dim AHArticle As MSHTML.IHTMLElement
Dim AHEuros As MSHTML.IHTMLElementCollection
Dim AHCents As MSHTML.IHTMLElementCollection
Dim AHPriceEuro As Double
Dim AHPriceCent As Double
Dim AHPrice As Double
IE.Visible = False
IE.navigate "https://www.ah.nl/producten/product/wi3640/lu-bastogne-biscuits-original"
Do While IE.readyState <> READYSTATE_COMPLETE
Loop
Set HTMLDoc = IE.document
'wait for the page to fully load to be able to get price data
Application.Wait Now + #12:00:03 AM#
Set AHArticles = HTMLDoc.getElementsByTagName("article")
For Each AHArticle In AHArticles
If AHArticle.getAttribute("data-sku") = "wi3640" Then
Set AHEuros = AHArticle.getElementsByClassName("price__integer")
Set AHCents = AHArticle.getElementsByClassName("price__fractional")
AHPriceEuro = AHEuros.Item(0).innerText
AHPriceCent = AHCents.Item(0).innerText
AHPrice = AHPriceEuro + (AHPriceCent / 100)
Debug.Print AHPrice
Exit For
End If
Next AHArticle
IE.Quit
End Sub
以下 XML HTTP 请求未提供所需的输出(立即调试屏幕中未打印任何价格):
Sub Get_Product_Price_AH_XML()
Dim XMLReq As New MSXML2.XMLHTTP60
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim AHArticles As MSHTML.IHTMLElementCollection
Dim AHArticle As MSHTML.IHTMLElement
Dim AHEuros As MSHTML.IHTMLElementCollection
Dim AHCents As MSHTML.IHTMLElementCollection
Dim AHPriceEuro As Double
Dim AHPriceCent As Double
Dim AHPrice As Double
XMLReq.Open "GET", "https://www.ah.nl/producten/product/wi3640/lu-bastogne-biscuits-original", False
XMLReq.send
If XMLReq.Status <> 200 Then
MsgBox "Problem" & vbNewLine & XMLReq.Status & " - " & XMLReq.statusText
Exit Sub
End If
HTMLDoc.body.innerHTML = XMLReq.responseText
Application.Wait Now + #12:00:03 AM#
Set AHArticles = HTMLDoc.getElementsByTagName("article")
For Each AHArticle In AHArticles
If AHArticle.getAttribute("data-sku") = "wi3640" Then
Set AHEuros = AHArticle.getElementsByClassName("price__integer")
Set AHCents = AHArticle.getElementsByClassName("price__fractional")
AHPriceEuro = AHEuros.Item(0).innerText
AHPriceCent = AHCents.Item(0).innerText
AHPrice = AHPriceEuro + (AHPriceCent / 100)
Debug.Print AHPrice
Exit For
End If
Next AHArticle
End Sub
【问题讨论】:
标签: excel vba web-scraping xmlhttprequest screen-scraping