我想通过vba捕获网站中的锚点元素。
我同时尝试了MSHTML.IHTMLAnchorElement和MSHMTL.IHTMLBUttonELement,但无论哪种方式都会在Set行上出错。有人能描述一下下面的代码出了什么问题吗?
Sub goToWhtSpp()
Dim ie As New SHDocVw.InternetExplorer
ie.Visible = True
ie.navigate "https://cooperatordirectory.com/"
Do While ie.readyState <> READYSTATE_COMPLETE Or ie.Busy
Loop
Dim doc As MSHTML.HTMLDocument
Set doc = ie.document
Application.Wait 3000
URL = "https://cooperatordirectory.com/search_results?location_value=Florida&adm_lvl_1_sn=FL&stateSearchLN=Florida&country_sn=US&location_type=administrative_area_level_1&stateSearch=FL&swlat=24.396308&nelat=31.000968&swlng=-87.634896&nelng=-79.974306&lat=27.6648274&lng=-81.5157535&faddress=Florida%2C+USA&place_id=ChIJvypWkWV2wYgR0E7HW9MTLvc"
ie.navigate URL
Dim aelement As MSHTML.IHTMLAnchorElement
Set aelement = doc.getElementsByClassName("btn btn-primary btn-block") ' err line
Dim btn As MSHTML.IHTMLButtonElement
Set btn = doc.getElementsByClassName("btn btn-primary btn-block") ' err line
Debug.Print btn.Value
End Sub
<a class="btn btn-primary btn-block" href="/pro/20220324090906/connect">Send Message</a>
您希望在每次.navigate
之后等待页面加载。在这种情况下,您只需要一个.navigate
并等待。
getElementsByClassName()
返回的集合不是单个节点。因此,您的类型声明、随后的SET
对此类型的尝试以及随后查看.value
属性的尝试都将失败。.value
是单个节点的属性。
如果你想要第一个";按钮";href然后索引到正确类型的变量并调用.item(0)
,或者更有效地使用ie.document
的querySelector()
方法并传入多值类的单个类(仍然正确标识目标元素的类(。
Dim anchors As IHTMLElementCollection
Set anchors = .document.getElementsByClassName("btn-primary")
Dim anchor As IHTMLAnchorElement
Set anchor = .document.getElementsByClassName("btn-primary").Item(0)
Option Explicit
Public Sub PrintMessageUrl()
Const URL As String = "https://cooperatordirectory.com/search_results?location_value=Florida&adm_lvl_1_sn=FL&stateSearchLN=Florida&country_sn=US&location_type=administrative_area_level_1&stateSearch=FL&swlat=24.396308&nelat=31.000968&swlng=-87.634896&nelng=-79.974306&lat=27.6648274&lng=-81.5157535&faddress=Florida%2C+USA&place_id=ChIJvypWkWV2wYgR0E7HW9MTLvc"
Dim ie As SHDocVw.InternetExplorer
Set ie = New SHDocVw.InternetExplorer
With ie
.Visible = True
.navigate URL
Do While .readyState <> READYSTATE_COMPLETE Or .Busy: DoEvents: Loop
Debug.Print .document.querySelector(".btn-primary").href
.Quit
End With
End Sub