【问题标题】:How do I use 'getelementsbyclassname' when there's a number of the same class name?当有多个相同的类名时,如何使用“getelementsbyclassname”?
【发布时间】:2019-10-01 05:53:21
【问题描述】:

我正在尝试使用“span”标签上的 getelementsbyclassname 解析内部文本。但是有几个不同的内部文本与相同的类名匹配。如何解析内部文本?

https://finance.naver.com/item/sise_day.nhn?code=063760 -> 是我试图从中解析的 Internet Explorer 文档。

我要获取具体的内文“15,550”,即昨天的收盘价。

enter image description here

【问题讨论】:

    标签: vba internet-explorer web-scraping getelementsbyclassname


    【解决方案1】:

    尝试参考下面的示例代码可能会帮助您找到内部文本 = 15,550。

    Sub demo()
    Dim element As IHTMLElement
    Dim elements As IHTMLElementCollection
    Dim ie As InternetExplorer
    Dim val, val1 As String
    Dim html As HTMLDocument
    val = "15,550"
    
    
    Set ie = New InternetExplorer
    
    ie.Visible = True
    
    ie.Navigate "https://finance.naver.com/item/sise_day.nhn?code=063760"
    'Wait until IE has loaded the web page
    
    Do While ie.ReadyState <> READYSTATE_COMPLETE
    
    
    DoEvents
    
    Loop
    
    Set html = ie.document
    
    Set elements = html.getElementsByClassName("tah p11")
    
    Dim count As Long
    Dim erow As Long
    count = 1
    For Each element In elements
    If element.className = "tah p11" Then
    erow = Sheet1.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row
    val1 = html.getElementsByClassName("tah p11")(count).innerText
    
    If val = val1 Then
    Cells(erow, 1) = html.getElementsByClassName("tah p11")(count).innerText
    
    End If
    count = count + 1
    End If
    Next element
    End Sub
    

    输出:

    这只是一个示例代码供您参考。此外,您可以尝试修改代码以获得所需的输出。

    【讨论】:

      【解决方案2】:

      在表格中定位时,通过nth-of-type css 选择器使用行和列索引。你想要第 4 行,第 2 列。鉴于现代网站为此进行了优化,我使用 css 选择器作为一种更快的方法。

      ie.document.querySelector(".type2 tr:nth-of-type(4) td:nth-of-type(2)").innerText
      

      你可以简单地缩短为

      tr:nth-of-type(4) td:nth-of-type(2)
      

      作为页面上具有此坐标的第一个表格。

      我没有看到任何有用的信息,但也许还可以查看APIs

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-10
        • 1970-01-01
        相关资源
        最近更新 更多