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

如何在C#(Xamarin Forms)中用HTML AgilityPack获取表格InnerHTML

用HTML Agility Pack提取指定Class的表格内容(C#)

没问题,我来帮你搞定这个需求!既然你已经用HTML Agility Pack解析了文档,接下来只要定位到目标表格,再遍历它的行和单元格就能提取内容了。下面是具体的步骤和代码示例:

1. 确保已引用HTML Agility Pack

首先确认你已经通过NuGet安装了HtmlAgilityPack包,如果还没装,在NuGet包管理器里搜索安装就行。

2. 定位目标表格节点

你提到已经获取了id为"recipe-incredients"的节点,但需要提取class为"recipe-incredients"的表格。这里分两种情况处理:

情况1:直接从整个文档中查找表格

如果不需要依赖已有的父节点,可以直接用XPath或LINQ定位class匹配的表格:

// 假设你已经加载好HTML文档到doc变量中
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(yourHtmlContent); // 替换成你的HTML字符串,或者用doc.Load()加载本地文件

// 方法一:用XPath选择class包含"recipe-incredients"的table
var ingredientTable = doc.DocumentNode.SelectSingleNode("//table[contains(@class, 'recipe-incredients')]");

// 方法二:用LINQ查询(更直观,避免多class值干扰)
var ingredientTable = doc.DocumentNode.Descendants("table")
    .FirstOrDefault(t => 
        t.GetAttributeValue("class", "")
          .Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
          .Contains("recipe-incredients")
    );

⚠️ 注意:用Split判断class是为了避免多个class值的干扰(比如元素class是"recipe-incredients table-bordered"),如果你的目标class是唯一的,也可以简化用Contains。

情况2:从已获取的父节点下查找表格

如果你想在之前拿到的id为"recipe-incredients"的节点里找表格,只需要把查询范围换成这个父节点:

// 假设parentNode是你已获取的id为"recipe-incredients"的节点
var ingredientTable = parentNode.Descendants("table")
    .FirstOrDefault(t => 
        t.GetAttributeValue("class", "")
          .Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
          .Contains("recipe-incredients")
    );

3. 提取表格内容

找到表格节点后,就可以遍历它的行(<tr>)和单元格(<td>/<th>)来提取文本了:

if (ingredientTable != null)
{
    // 先提取表头(如果有<th>的话)
    var headers = ingredientTable.Descendants("th")
        .Select(header => header.InnerText.Trim())
        .ToList();
    
    // 遍历所有数据行
    foreach (var row in ingredientTable.Descendants("tr"))
    {
        // 提取当前行的所有单元格文本(自动忽略表头行,如果表头用<th>的话)
        var cellTexts = row.Descendants("td")
            .Select(cell => 
                // 清理文本中的多余空格和换行
                System.Text.RegularExpressions.Regex.Replace(cell.InnerText, @"\s+", " ").Trim()
            )
            .ToList();
        
        // 这里可以根据你的需求处理单元格内容,比如存入模型或打印
        if (cellTexts.Any())
        {
            // 示例:打印行内容
            Console.WriteLine(string.Join(" | ", cellTexts));
            // 或者存入自定义集合:
            // yourIngredientList.Add(new Ingredient { Name = cellTexts[0], Quantity = cellTexts[1] });
        }
    }
}
else
{
    // 处理表格不存在的情况
    Console.WriteLine("未找到目标表格");
}

小提示

  • 如果表格里有嵌套的HTML元素(比如<span>、<strong>),InnerText会自动提取所有子节点的文本,不用额外处理。
  • 要是需要更精确的文本提取,可以针对特定子节点获取内容,比如cell.SelectSingleNode("./span").InnerText。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:40:56