首页 > 解决方案 > 如何提取带有特定文本的 URL?

问题描述

我需要提取包含 URL 特定行的 URL,例如/example/example1/newexample/

<a onfocus="OnLink(this)" href="/example/example1/newexample/testing.aspx">Testing</a>

我当前的代码返回页面上的所有超链接。我如何仅使用/example/example1/newexample/提取这些链接

Sub GetAllLinks()
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
    url_name = Sheet1.Range("B2")
    If url_name = "" Then Exit Sub
    IE.navigate (url_name)

    Do
        DoEvents
    Loop Until IE.readyState = READYSTATE_COMPLETE

    Set AllHyperlinks = IE.document.getElementsByTagName("A")
    Sheet1.ListBox1.Clear

    For Each Hyperlink In AllHyperlinks
        Sheet1.ListBox1.AddItem (Hyperlink)
    Next

    IE.Quit
    MsgBox "Completed"
End Sub

标签: excelvba

解决方案


使用 CSS 选择器更容易避免初始循环和目标,然后循环返回的 nodeList

Dim aNodeList As Object,  i As Long
Set aNodeList = IE.document.querySelector("a[href^='/example/example1/newexample/']")

For i = 0 To aNodeList.Length-1
   Debug.print aNodeList.item(i).getAttribute("href")
Next i

方法以^开头,因此a[href^='/example/example1/newexample/']是寻找带有a标签的元素,其中包含href以开头的属性'/example/example1/newexample/'

这是您的 html 示例中的 CSS 选择器:

CSS 查询


推荐阅读