使用VBA从Yahoo Finance检索数据(资产负债表而非股票)

我尝试了几天,使用VBA指令从Yahoo财务获取公司的资产负债表数据,例如“ .getElementsByTagName”,但该方法不起作用...什么也没发生,我被卡住了...

有什么想法吗?参见下面的代码:

Sub Get_Data()
Dim url As String
Dim http As Object
Dim TR_col As Object,Tr As Object
Dim TD_col As Object,Td As Object
Dim row As Long,col As Long
Dim html As Object
Dim tbl As Object
'

On Error Resume Next

Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0") 'CreateObject("MSXML2.ServerXMLHTTP.6.0")
    url = "https//finance.yahoo.com/quote/AAPL/balance-sheet?p=AAPL"
    http.Open "POST",url,False
    http.setRequestHeader "Content-Type","text/xml"
    http.Send
    MsgBox http.responseText

Set html = CreateObject("htmlfile")
html.body.innerHTML = http.responseText
Set tbl = html.getElementById("Pos(r)")

    row = 1
    col = 1
    Set TR_col = html.getElementsByTagName("TR")
    For Each Tr In TR_col
        Set TD_col = Tr.getElementsByTagName("TD")
        For Each Td In TD_col
            Cells(row,col) = Td.innerText
            col = col + 1
        Next
        col = 1
        row = row + 1
    Next

End Sub 
sinkysahine 回答:使用VBA从Yahoo Finance检索数据(资产负债表而非股票)

我认为这可以解决问题。我必须在网址中添加“:”,将“ POST”更改为“ GET”并设置2个请求标头,第一个是cookie,我认为它将在一年后过期,可以通过运行以下命令找到它:

Cells(1,1) = http.responseText
Dim responseHeader As String
responseHeader = http.getAllResponseHeaders
Cells(2,1) = responseHeader

并读取setcookie行。然后,我只是将其硬编码到请求标头中。运行代码如下:

Sub Get_Data()
Dim url As String
Dim http As Object
Dim TR_col As Object,Tr As Object
Dim TD_col As Object,Td As Object
Dim row As Long,col As Long
Dim html As Object
Dim tbl As Object

'On Error Resume Next

Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0") 
'CreateObject("MSXML2.ServerXMLHTTP.6.0")
url = "https://uk.finance.yahoo.com/quote/AAPL/balance-sheet?p=aapl"
http.Open "GET",url,False
http.setRequestHeader "Cookie","B=22guonpesgnqg&b=3&s=5p"
http.setRequestHeader "Content-Type","text/xml"
http.Send
Cells(1,1) = http.responseText
'Dim responseHeader As String
'responseHeader = http.getAllResponseHeaders
'Cells(2,1) = responseHeader

Set html = CreateObject("htmlfile")
html.body.innerHTML = http.responseText
Set tbl = html.getElementById("Pos(r)")
row = 1
col = 1
Set TR_col = html.getElementsByTagName("TR")
For Each Tr In TR_col
    Set TD_col = Tr.getElementsByTagName("TD")
    For Each Td In TD_col
        Cells(row,col) = Td.innerText
        col = col + 1
    Next
    col = 1
    row = row + 1
Next

End Sub

希望这就是您想要的,返回的数据看起来类似于我的浏览器显示的内容。

本文链接:https://www.f2er.com/3128429.html

大家都在问