[英]Excel VBA : How to copy href from HTML by referencing the class name
<a href="?contractDate=&6578706f7274=1&currency=MYR&currPage=1&method.searchM2MTotal=Retrieve&d-448075-e=2&netType=M&contractFromDate=13%2F05%2F2016&contractToDate=13%2F05%2F2016"><span class="export excel">Excel </span></a>|
How can I copy the href in this HTML via Excel VBA?如何通过 Excel VBA 复制此 HTML 中的 href?
This is my code, but it doesn't work.这是我的代码,但它不起作用。
Set Export = ie.Document.all("export excel")
URL = Export.href
ie.Navigate URL
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.