Getting <a> tags and attribute using htmlagilitypack using vb.net

I have this code

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

but i get an error Object reference not set to an instance of an object.

Does the document contain at least one tag tag? how can i check if an attribute is coming out?

I tried this if link.HasAttributes("title") thenand got another error

Public ReadOnly Property HasAttributes() As Boolean' has no parameters and its return type cannot be indexed.

+1
source share
2 answers

If HtmlAgilityPack supports this XPATH selector, you can replace it //awith//a[@href]

For Each link as HtmlNode In root.SelectNodes("//a[@href]")
    doSomething()
Next

Otherwise, you can use the property Attributes:

For Each link as HtmlNode In root.SelectNodes("//a")
    If link.Attributes.Any(Function(a) a.Name = "href") Then doSomething()
Next
+1
source
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

In addition, you can check the attributes: link.Attributes ["title"] if null, then it does not have an attribute. Same link .Attributes ["href"] etc.

link.HasAttributes , , bool.

0

Source: https://habr.com/ru/post/1782125/


All Articles