http://www.asx.com.au 网站有一个可用的 API。我在 Chrome 中为其中一家公司打开了一个页面 - AMC 通过链接 http://www.asx.com.au/asx/share-price-research/company/AMC,然后打开开发人员工具窗口 (F12)、网络选项卡,并在页面加载后检查列表中的 XHR在我点击每个部分之后。我发现了几个以 JSON 格式返回数据的 URL:
要查看呈现数据的结构,可以将响应内容复制并粘贴到任何 JSON 查看器(例如,此在线工具 http://jsonviewer.stack.hu)。
您可以使用下面的 VBA 代码来解析来自 URL https://www.asx.com.au/asx/1/share/AMC/prices 的响应并输出结果。 将JSON.bas模块导入VBA项目进行JSON处理。
Option Explicit
Sub Test_query_ASX()
Const Transposed = False ' Output option
Dim sCode As String
Dim sInterval As String
Dim sCount As String
Dim sJSONString As String
Dim vJSON As Variant
Dim sState As String
Dim aRows()
Dim aHeader()
sCode = "AMC"
sInterval = "daily"
sCount = "10"
' Get JSON via API
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://www.asx.com.au/asx/1/share/" & sCode & "/prices?interval=" & sInterval & "&count=" & sCount, False
.Send
sJSONString = .ResponseText
End With
' Parse JSON response
JSON.Parse sJSONString, vJSON, sState
If sState = "Error" Then
MsgBox "Invalid JSON"
Exit Sub
End If
' Pick core data
vJSON = vJSON("data")
' Convert each data set to array
JSON.ToArray vJSON, aRows, aHeader
' Output array to worksheet
With ThisWorkbook.Sheets(1)
.Cells.Delete
If Transposed Then
Output2DArray .Cells(1, 1), WorksheetFunction.Transpose(aHeader)
Output2DArray .Cells(1, 2), WorksheetFunction.Transpose(aRows)
Else
OutputArray .Cells(1, 1), aHeader
Output2DArray .Cells(2, 1), aRows
End If
.Columns.AutoFit
End With
MsgBox "Completed"
End Sub
Sub OutputArray(oDstRng As Range, aCells As Variant)
With oDstRng
.Parent.Select
With .Resize(1, UBound(aCells) - LBound(aCells) + 1)
.NumberFormat = "@"
.Value = aCells
End With
End With
End Sub
Sub Output2DArray(oDstRng As Range, aCells As Variant)
With oDstRng
.Parent.Select
With .Resize( _
UBound(aCells, 1) - LBound(aCells, 1) + 1, _
UBound(aCells, 2) - LBound(aCells, 2) + 1)
.NumberFormat = "@"
.Value = aCells
End With
End With
End Sub
运行Sub Test_query_ASX() 处理数据。对我来说,Sheet1 上的输出如下:
通过该示例,您可以通过列出的 URL 从 JSON 响应中提取所需的数据。顺便说一句,类似的方法适用于in other answers。
更新
在网站上进行一些更改后,需要使用https://www.asx.com.au/asx/...而不是http://www.asx.com.au/b2c-api/...,所以我修复了上述所有网址。