【问题标题】:getting <a> tags and attribute with htmlagilitypack with vb.net使用 htmlagilitypack 和 vb.net 获取 <a> 标记和属性
【发布时间】:2011-06-06 13:05:12
【问题描述】:

我有这个代码

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.

【问题讨论】:

    标签: vb.net html-agility-pack


    【解决方案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
    

    【讨论】:

    • @jay 不是只提取链接,而是标题属性和内部文本,那么我该怎么做呢?
    • @Smith HasAttributes 不是方法,而是属性——不能使用括号和参数。还有一个Attributes 属性,它将返回与给定元素节点关联的所有属性。哪一行代码导致NullReferenceException
    • @Smith 更多关于您的问题,请参阅我的第二个示例。在For…Each 块中,您可以检查link.Attributes 以查看它是否包含href 属性,但您也可以检查其他属性和/或使用link.InnerText 属性来获取锚标记的内部文本.
    • @jay 谢谢如果我想检查它有titlealt 或其他属性,我该如何进行检查?
    • @Smith 对于 .NET 2.0,您只需要对 link.Attributes 执行 For Each 循环,并检查每个 .Name
    【解决方案2】:
    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,则没有属性。 相同的link.Attributes["href"] 等。

    Property link.HasAttributes 只显示标签有任何属性,它是布尔值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 2015-11-17
      • 1970-01-01
      相关资源
      最近更新 更多