You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Html Agility Pack无法提取HTML文档中所有<p>标签的问题

解决Html Agility Pack提取

标签返回null的问题

问题场景

使用Html Agility Pack提取HTML文档中的<p>标签时,SelectNodes("//p")返回null,无法正常遍历节点。

原代码示例

var doc = new HtmlDocument();
doc.Load(@"c:\Webs\test.html");
var nodes = doc.DocumentNode.SelectNodes("//p");

foreach ( var paragraph in nodes ) { 
    Console.WriteLine($"paragraph {paragraph.InnerText}");
}

对应HTML文档

<!DOCTYPE html>

<html>
<head>
</head>
<body>
     <p>I am a paragraph</p>
     <p>I am a paragraph</p>
     <h1>I am an H1</h1>
     <p>I am a paragraph</p>
     <p>I am a paragraph</p>
     <p>I am a paragraph</p>
     <h1>I am an H1</h1> 
</body>
</html>

解决方案

以下是几个可行的解决办法:

  • 检查文件路径与状态
    确认c:\Webs\test.html路径拼写正确,文件确实存在且未被其他程序占用。

  • 指定文件编码加载
    若HTML文件使用非默认编码(如GB2312),加载时显式指定编码避免解析异常:

    var doc = new HtmlDocument();
    doc.Load(@"c:\Webs\test.html", Encoding.UTF8); // 替换为文件实际编码
    
  • 用Descendants方法替代XPath
    Descendants方法更稳定,找不到节点时返回空集合而非null,避免空引用报错:

    var doc = new HtmlDocument();
    doc.Load(@"c:\Webs\test.html");
    var nodes = doc.DocumentNode.Descendants("p");
    
    foreach (var paragraph in nodes)
    {
        Console.WriteLine($"paragraph {paragraph.InnerText}");
    }
    
  • 添加null判断(兼容XPath写法)
    坚持用XPath的话,先判断nodes是否为null再遍历:

    var doc = new HtmlDocument();
    doc.Load(@"c:\Webs\test.html");
    var nodes = doc.DocumentNode.SelectNodes("//p");
    
    if (nodes != null)
    {
        foreach (var paragraph in nodes)
        {
            Console.WriteLine($"paragraph {paragraph.InnerText}");
        }
    }
    
  • 更新Html Agility Pack版本
    旧版本可能存在解析bug,通过NuGet安装最新版本,提升兼容性。

内容的提问来源于stack exchange,提问作者Max

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:15:12