Excel VBA:如何通过引用类名从HTML复制href [英] Excel VBA : How to copy href from HTML by referencing the class name

查看:337
本文介绍了Excel VBA:如何通过引用类名从HTML复制href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<a href="?contractDate=&amp;6578706f7274=1&amp;currency=MYR&amp;currPage=1&amp;method.searchM2MTotal=Retrieve&amp;d-448075-e=2&amp;netType=M&amp;contractFromDate=13%2F05%2F2016&amp;contractToDate=13%2F05%2F2016"><span class="export excel">Excel </span></a>| 

如何通过Excel VBA复制此HTML中的href?

How can I copy the href in this HTML via Excel VBA?

这是我的代码,但它不起作用。

This is my code, but it doesn't work.

Set Export = ie.Document.all("export excel")
    URL = Export.href
    ie.Navigate URL


推荐答案

这个代码你应该在调试模式下走过...它更多的是教学用途而不是生产,但它会做你想要的。我使用Google作为测试网站。

This code you should walk through in debug mode ... it's more for instructional use than for production, but it will do what you want from it. I used Google as a test site.

Sub Test()
Dim Browser As SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument
Dim Link As String, Target As Object

    Link = "http://www.google.com"

    ' start browser
    Set Browser = New SHDocVw.InternetExplorer
    Browser.Visible = True
    ' wait a bit

    Browser.Navigate Link
    ' wait a bit

    Set HTMLDoc = Browser.Document
    ' wait a bit

    Set Target = GetElementByTagAndClassName(HTMLDoc, "SPAN", "gbtb2")

    If Not (Target Is Nothing) Then
        ' test here if parent really is a <a>
        Debug.Print Target.parentElement.href
        ' ta-taaaa!!!
    End If

End Sub

' get element by tag and attribute value
Function GetElementByTagAndClassName(Doc As MSHTML.HTMLDocument, ByVal Tag As String, ByVal Match As String) As MSHTML.IHTMLElement
Dim ECol As MSHTML.IHTMLElementCollection
Dim IFld As MSHTML.IHTMLElement


    Set GetElementByTagAndClassName = Nothing

    Set ECol = Doc.getElementsByTagName(Tag)
    For Each IFld In ECol
        ' Debug.Print IFld.className
        If IFld.className = Match Then
            Set GetElementByTagAndClassName = IFld
            Exit Function
        End If
    Next
End Function

这篇关于Excel VBA:如何通过引用类名从HTML复制href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆