【问题标题】:HtmlAgilityPack - Attributes property always emptyHtmlAgilityPack - Attributes 属性始终为空
【发布时间】:2013-12-03 12:06:58
【问题描述】:

我正在使用 HtmlAgilityPack 来解析一些 html,并且我正在尝试提取图像标签的样式属性。下面是一些示例代码:

  Dim hd As New HtmlDocument()
  hd.LoadHtml("<img style='float:left;' />")
  Dim s As String = hd.DocumentNode.GetAttributeValue("style", String.Empty)

问题是字符串s总是空的,当我在调试中检查hd.DocumentNode时发现属性集合也是空的并且HasAttributes设置为false。

这可能与我使用 html 片段而不是完整文档填充 html 文档对象的方式有关吗?

欢迎提出任何建议。

【问题讨论】:

    标签: .net vb.net html-agility-pack


    【解决方案1】:

    找到了解决办法。

    我做了一个假设,因为我加载的 html 只是一个元素,所以文档节点就是那个单个元素。事实上,我仍然需要使用 XPath 选择元素,然后才能引用它并能够访问它的属性。解决方案:

    Dim hd As New HtmlDocument()
    hd.LoadHtml("<img style='float:left;' />")
    Dim s As String = hd.DocumentNode.SelectSingleNode("//img").GetAttributeValue("style", String.Empty)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 2021-07-04
      • 2021-10-07
      相关资源
      最近更新 更多