AriKari
AriKari

Reputation: 323

Not able to get element by class name

I am trying to get the number of votes of Buy, Sell, Neutral in the Technical Summary widget on this page: https://in.tradingview.com/symbols/NSE-TCS/

The elements are these

<span class="tv-widget-technicals__counter-number redColor">2</span>

<span class="tv-widget-technicals__counter-number neutralColor">10</span>

 <span class="tv-widget-technicals__counter-number brandColor">8</span>

I tried different things but I don't know how to access these elements. I even tried looping through all span elements but there didn't show up in the list.

I have added what I have tried so far please let me know how can I solve this.

Sub Test_Macro()

Dim i As Long, j As Long, fD As Long
Dim symBol As String, urL As String, hdoc
Dim oHtml As HTMLDocument
Dim oElement As Object
Dim dados

With DATA

    fD = .Range("A" & .Rows.Count).End(xlUp).Row
    Set oHtml = New HTMLDocument

    With CreateObject("WINHTTP.WinHTTPRequest.5.1")
        For i = 2 To fD

            symBol = Trim(Replace(Replace(DATA.Range("A" & i).Value, "-", "_"), "&", "_"))
            urL = "https://in.tradingview.com/symbols/NSE-" & symBol

            .Open "GET", urL, False
            .send
            oHtml.body.innerHTML = .responseText

            Stop

            Set dados = oHtml.getElementsByClassName("tv-site-widget ").Item(1).getElementsByTagName("span")
            j = 1
            For Each oElement In dados
                DATA.Range("F" & j) = oElement.innerText
                j = j + 1
                'Debug.Print oElement.innerHTML
            Next oElement
            Stop
        Next i
    End With

End With

End Sub

Upvotes: 1

Views: 5324

Answers (1)

SIM
SIM

Reputation: 22440

Try the below way. The content you are after gets generated dynamically. Even if you use any browser simulator like IE, you can't grab the content unless you make your browser wait a little while for the numbers to load. The bottom line is you can't fetch the desired output using xmlhttp, winhttp or serverxmlhttp request as they don't deal with dynamic content. Give it a shot:

Sub TestMacro()
    Const URL As String = "https://in.tradingview.com/symbols/NSE-TCS/"
    Dim IE As New InternetExplorer, oHtml As HTMLDocument, post As Object, R&

    With IE
        .Visible = True
        .navigate URL
        While .Busy Or .readyState < 4: DoEvents: Wend
        Set oHtml = .document
    End With

    Application.Wait Now + TimeValue("00:00:05")

    For Each post In oHtml.getElementsByClassName("tv-widget-technicals__counter-wrapper")
        With post.getElementsByTagName("span")
            R = R + 1: Cells(R, 1) = .Item(0).innerText
        End With
    Next post
End Sub

Output at this moment:

2
10
14

Reference to add:

Microsoft Internet Controls
Microsoft HTML Object Library

Upvotes: 4

Related Questions