如何在VBA Web抓取中从HTML代码中提取<tspan>元素

时间:2019-06-12 00:04:09

标签: html excel vba web-scraping

我正在尝试使用带有VBA的HTML网络抓取从网页中提取数据。我在其他站点上都取得了成功,但是该站点中的数据包含在标记为tspan的代码行中,我似乎无法从中获取数据。

HTML代码如下所示(很长的代码,很抱歉,不确定是否相关):

<div class="Classname">
    <svg width ="100%" height="100%" fill="code" stroke="100%" stroke="code" viewBox="numbers" class="undefined">
         <polygon fill="transparent" points="numbers"></polygon?
             <text y="100" dy="#s">
                <tspan x="100" text-anchor="middle">1</tspan>

我想要的值是的最后一行中的1。导航到正确的网页等后,我用来提取它的代码是:

Dim text As String
text=IE.document.GetElementsByClassname("Classname")(0).GetElementsByTagname("tspan")(0).innertext

我还尝试了在svg代码行中出现的类名“未定义”的情况。无论哪种方式,我都会收到错误91。

编辑:我现在已经尝试嵌套GetElementsByTagName,仍然出现错误

text=IE.document.GetElementsByClassname("C")(0).GetElementsByTagname("svg")(0).GetElementsByTagname("polygon")(0).GetElementsByTagname("text")(0).GetElementsByTagname("tspan")(0).innertext

3 个答案:

答案 0 :(得分:0)

已解决。该类名有一个下划线,实际上是2个下划线。 __ vs _,很难说出区别。嵌套的getelementsbytagname可以解决问题。

答案 1 :(得分:0)

或者,您也可以使用querySelector方法...

text = IE.document.querySelector("tspan[text-anchor='middle']").innerText

希望这会有所帮助!

答案 2 :(得分:0)

这是一种更直接,更快捷的方法

Option Explicit
Public Sub GetData()
    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate2 "https://www.tipranks.com/stocks/mmm/stock-analysis"

        While .Busy Or .readyState < 4: DoEvents: Wend
        Do 'could use timed loop here to handle infinite looping risk
            Set elem = .document.querySelectorAll("tspan")
        Loop While elem.Length = 0
        Debug.Print elem.item(0).innerText
        .Quit
    End With
End Sub