You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从网页元素中获取完整正确的URL?

如何获取网页链接的完整正确URL?

我正在尝试找到获取链接完整正确URL的方法。有时使用item.href能得到完整URL,但有时仅返回about:something、about:..something或about:../something这类格式。

在当前场景中,我遍历目标URL(https://www.w3schools.com/excel/index.php)下的所有链接,想要获取文本含“VLOOKUP”的链接的完整URL。当前代码返回的结果是about:excel_vlookup.php,若直接将基础URL与替换掉“about:”后的内容拼接,会得到错误的https://www.w3schools.com/excel/index.phpexcel_vlookup.php,而正确的完整URL应为鼠标悬停时显示的https://www.w3schools.com/excel/excel_vlookup.php。

请问该如何实现?

Sub full_url()
Dim htmlDoc As New HTMLDocument
Dim links As Object
Dim i As Integer

    With New ServerXMLHTTP60
        .Open "Get", "https://www.w3schools.com/excel/index.php", False
        .send
        htmlDoc.body.innerHTML = .responseText
    End With
        
    Set links = htmlDoc.body.getElementsByTagName("a")
    
    With links
        For i = 0 To .Length - 1
            If .Item(i).innerText Like "*VLOOKUP*" Then
                Debug.Print .Item(i).href
            End If
        Next
    End With

End Sub

更新

基于@taller的代码,该代码在处理about:something格式的href时有效,但处理完整URL时仍需调整。

Sub full_url1()
    Dim htmlDoc As New HTMLDocument
    Dim links As Object
    Dim i As Integer, sUrl As String, aTxt, iCnt As Long
    Const PREFIX = "about:"
    sUrl = "https://www.w3schools.com/excel/index.php"
    aTxt = Split(sUrl, "/")
    iCnt = UBound(aTxt)
    With New ServerXMLHTTP60
        .Open "Get", sUrl, False
        .send
        htmlDoc.body.innerHTML = .responseText
    End With
    
    Set links = htmlDoc.body.getElementsByTagName("a")
    
    With links
        For i = 0 To .Length - 1
            If .Item(i).innerText Like "*Spaces*" Then
                href = .Item(i).href
                If InStr(1, href, "https://") = 1 Then
                    Debug.Print .Item(i).href
                Else
                    aTxt(iCnt) = Mid(href, Len(PREFIX) + 1)
                    Debug.Print Join(aTxt, "/")
                End If
                Exit For
            End If
        Next
    End With
End Sub

内容的提问来源于stack exchange,提问作者Rasec Malkic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 11:05:20