以下内容用于解决您的这部分问题:
Excel 应该会自动导入价格历史图表数据
您正在戳的页面提供了一种非常方便的方式来下载您感兴趣的数据。您可以通过向相应的服务器发送XML HTTP request (XHR) 来完成。
通过在浏览器的开发人员工具中检查网络流量,您可以轻松看到这一点。在那里,您将看到加载页面时发送的一堆请求。其中大多数与请求样式表 (css) 或 png 和 gif 文件有关。其他人调用需要执行的脚本(js)。您需要的是XHR 请求,它以JSON 格式获取数据作为响应。
仔细查看请求,您会发现它由 URL、标头和正文组成。正文包含请求的参数。在这种情况下,您只需要一个product code。
鉴于上述情况,您可以在 VBA 中构造请求并将其发送到服务器以获取感兴趣的数据。更改产品代码参数将为您获取每个产品的相应数据。
为此,您需要将JSON parser 导入您的项目。按照说明操作即可。
那么你需要一些参考资料(VB 编辑器>工具>参考资料):
- Microsoft WinHTTP Services 5.1 版(用于创建和操作 HTTP 请求)
- Microsoft 运行时脚本(JSON 解析器需要)
那么代码应该是这样的:
Option Explicit
Sub downloadPriceData()
Dim req As New WinHttpRequest
Dim URL As String, reqBody As String, productCode As String
Dim respTxt As String
Dim respJSON As Object
URL = "https://grieferwert.com/wp-admin/admin-ajax.php"
productCode = getProductCode("sand-dk") 'Changing the product name will get the corresponding data.
'productCode = "200" 'Hard coded version. Each product has its own code. You can see the code by inspectig the request's body as shown in the screenshots
reqBody = "action=wooPriceHistoryAjax&subaction=getGraph&product=" & productCode & "&period=1"
With req
.Open "POST", URL, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" 'This is the only header that's absolutely essential to the request
.send reqBody
respTxt = .responseText
End With
Set respJSON = JsonConverter.ParseJson(respTxt)
Debug.Print respJSON("status")
Debug.Print respJSON("json")("rows")(1)("price")("value") 'This prints the first data point. The structure of the JSON can be seen in the screenshot.
End Sub
Public Function getProductCode(productName As String) As String 'This functions finds the product code, given the name of the product
Dim req As New WinHttpRequest
Dim doc As New HTMLDocument
Dim div As HTMLDivElement
Dim URL As String
URL = "https://grieferwert.com/?product=" & productName
With req
.Open "GET", URL, False
.send
doc.body.innerHTML = .responseText
End With
Set div = doc.getElementById("ph_chart_container")
getProductCode = div.Attributes("data-product").Value
End Function
以上演示代码将只打印immediate window 中的一个数据点。将产品名称存储在工作表中并循环访问它们而不是循环访问链接将为您获取您感兴趣的所有产品的数据。
这应该让您开始着手获取其余数据。
编辑
编辑了最初的帖子,以包含一种根据产品名称自动获取产品代码的方法。