VBA:在HTML表格中从TD的innerhtml中提取href的有效方法

时间:2018-01-05 07:32:42

标签: html excel vba excel-vba

我从TD的innerHTML中提取href,它驻留在HTML表格中。

使用的网址: http://www.moneycontrol.com/india/mutualfunds/mfinfo/portfolio_holdings/MMO029

我从中获取数据的类tblporhd的表格。我正在使用MSXML2.XMLHTTP对象从网站中提取,我正在HTMLDocument加载它并且它正常工作。我怀疑的是我用来从表格中的一个单元格(TD)中提取href的方法。我正在将innerHTML传递给基于UDF的RegExp,如下所示。

strGetURL(objCell.innerHTML)

功能如下(工作):

Private Function strGetURL(strInput As String) As String
Dim RgEx As Object: Set RgEx = CreateObject("VBScript.RegExp")
Dim objMatches As Object
With RgEx
    .MultiLine = False
    .Global = True
    .Pattern = "href=(["" '])(.*?)\1"
End With

Set objMatches = RgEx.Execute(strInput)
If objMatches.Count <> 0 Then
    strGetURL = Replace(objMatches.Item(0).submatches.Item(1), "about:/", "http://www.moneycontrol.com/")
Else
End If

End Function

查询:

虽然我的代码有效,但有没有任何方法可以通过使用某些默认功能/语法或更好的方法获得相同的结果,这种方法已经可以在HTMLDocument Table Cell中处理了?

我搜索了互联网,但无法找到任何相关代码,因此发布了一个新问题。如果需要任何其他信息,请与我们联系。

2 个答案:

答案 0 :(得分:2)

我希望它能解决这个问题。立即尝试:

Sub TableData()
    Const base_url As String = "http://www.moneycontrol.com"
    Dim HTTP As New XMLHTTP60, html As New HTMLDocument
    Dim posts As Object, elem As Object, trow As Object

    With HTTP
        .Open "GET", "http://www.moneycontrol.com/india/mutualfunds/mfinfo/portfolio_holdings/MMO029", False
        .send
        html.body.innerHTML = .responseText
    End With

    Set posts = html.getElementsByClassName("tblporhd")(0)

    For Each elem In posts.getElementsByTagName("tr")
        For Each trow In elem.getElementsByTagName("td")
            With trow.getElementsByTagName("a")
                If .Length Then Cells(z + 1, 1) = base_url & Split(.Item(0).href, "about:")(1)
            End With
            y = y + 1: Cells(r + 1, y + 1) = trow.innerText
        Next trow
        y = 0
        r = r + 1
        z = z + 1
    Next elem
End Sub

答案 1 :(得分:0)

你的节点变量是objCell,并没有给出它的定义。对于大多数(所有?)HTML节点,将有innerhtml属性,但为什么不转换为MSHTML.HTMLAnchorElement类型的变量,然后使用锚点href属性?