如何从href属性获取URL

问题描述 投票:0回答:1

我无法从href属性获取URL。我用这个代码

Dim url As String = "http://example.com/"
Dim web As New HtmlWeb()
Dim doc As HtmlDocument = web.Load(url)

For Each item As HtmlNode In doc.DocumentNode.SelectNodes("//a/@href")
    If Not item Is Nothing Then
        Response.Write(item.OuterHtml)
    End If
Next

但它不起作用。

vb.net xpath html-agility-pack
1个回答
2
投票

由于href是一个属性,你需要把它放在方括号[]

记住属性在您搜索时会进入方括号。

//a[@href]

在你的情况下,你需要获得所有//a节点,然后检查HasAttributes("href"),最后,获得Attributes("href")

For Each item As HtmlNode In doc.DocumentNode.SelectNodes("//a")
    If Not item Is Nothing And item.HasAttributes("href") Then
        Response.Write(item.Attributes("href").Value)
    End If
Next
© www.soinside.com 2019 - 2024. All rights reserved.