我有这个代码
Dim htmldoc As HtmlDocument = New HtmlDocument()
htmldoc.LoadHtml(strPageContent)
Dim root As HtmlNode = htmldoc.DocumentNode
For Each link As HtmlNode In root.SelectNodes("//a")
If link.HasAttributes("href") Then doSomething() 'this doesn't work because hasAttributes only checks whether an element has attributes or not
Next
但收到错误 Object reference not set to an instance of an object.
该文档至少包含一个锚标记?我如何检查属性是否退出?
我试过这个if link.HasAttributes("title") then
并得到另一个错误
Public ReadOnly Property HasAttributes() As Boolean' has no parameters and its return type cannot be indexed.
答案 0 :(得分:1)
如果HtmlAgilityPack支持此XPATH选择器,则可以将//a
替换为//a[@href]
For Each link as HtmlNode In root.SelectNodes("//a[@href]")
doSomething()
Next
否则,您可以使用Attributes
属性:
For Each link as HtmlNode In root.SelectNodes("//a")
If link.Attributes.Any(Function(a) a.Name = "href") Then doSomething()
Next
答案 1 :(得分:0)
Dim htmldoc As HtmlDocument = New HtmlDocument()
htmldoc.LoadHtml(strPageContent)
Dim root As HtmlNode = htmldoc.DocumentNode
var nodes = root.SelectNodes("//a[@href and @title]")
if (nodes <> Null) Then
For Each link As HtmlNode In nodes
If link.HasAttributes("href") Then doSomething() 'this doesn't work because hasAttributes only checks whether an element has attributes or not
Next
end if
此外,您还可以检查属性: link.Attributes [“title”]如果为null,则没有属性。 相同的链接。属性[“href”]等等。
属性link.HasAttributes只显示该标签有任何属性,它是bool值。