【问题标题】:Not able to get element by class name无法通过类名获取元素
【发布时间】:2018-05-24 15:23:59
【问题描述】:

我正在尝试在此页面的技术摘要小部件中获取买入、卖出、中性的票数:https://in.tradingview.com/symbols/NSE-TCS/

元素就是这些

<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>

我尝试了不同的方法,但我不知道如何访问这些元素。我什至尝试遍历所有 span 元素,但没有出现在列表中。

我已经添加了到目前为止我尝试过的内容,请告诉我如何解决这个问题。

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

【问题讨论】:

    标签: vba excel getelementsbyclassname


    【解决方案1】:

    试试下面的方法。您所追求的内容是动态生成的。即使您使用任何浏览器模拟器,例如IE,您也无法抓取内容,除非您让浏览器等待一段时间以加载数字。底线是您无法使用 xmlhttp、winhttp 或 serverxmlhttp 请求获取所需的输出,因为它们不处理动态内容。试一试:

    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
    

    此时输出:

    2
    10
    14
    

    参考添加:

    Microsoft Internet Controls
    Microsoft HTML Object Library
    

    【讨论】:

    • 是否可以在没有 IE 的情况下执行此操作,因为它很慢。不过感谢您的回答。
    • 然后尝试使用 selenium。我已经在我的回答中详细说明了为什么 IE 在这种情况下是理想的。
    猜你喜欢
    • 1970-01-01
    • 2018-06-29
    • 2011-09-16
    • 1970-01-01
    • 2012-01-22
    • 2017-04-03
    • 2012-07-20
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多