【问题标题】:How to sanitize html with HtmlAgilityPack?如何使用 HtmlAgilityPack 清理 html?
【发布时间】:2017-12-21 11:09:11
【问题描述】:

我的网络爬虫遇到问题,基本上我需要在单元格team_a_col home 中获取十进制数:

<th>Med. goal subiti p/p</th>
<td class='team_a_col total'>0.76</td>
<td class='team_a_col home'>0.89
<td class='team_a_col away'>0.62</td></td>

所以结果应该是:0.89

但正如您所见,html 的结构不好,所以我没有得到0.89,而是使用此代码得到team_a_col away 的内容:

node.SelectSingleNode(".//td[@class='team_a_col home']").InnerText.Trim();

我怎样才能只得到 0.89? &lt;/td&gt; 应该在 &lt;team_a_col away.. 之前。

【问题讨论】:

  • 你现在使用的代码是什么?
  • @rene node.SelectSingleNode(".//td[@class='team_a_col home']").InnerText.Trim();
  • HtmlAgilityPack 旧且损坏,不如使用AngleSharp。至于格式错误的 HTML,除了尽力而为之外,任何库都无能为力——您可能不得不自己手动处理它。
  • @IanKemp 我无法更改库

标签: c# html-agility-pack


【解决方案1】:

您应该将HtmlDocument.FixNestedTags 设置为true

string html = "<th>Med. goal subiti p/p</th><td class='team_a_col total'>0.76</td><td class='team_a_col home'>0.89<td class='team_a_col away'>0.62</td></td>";

var doc = new HtmlAgilityPack.HtmlDocument
{
    OptionFixNestedTags = true,
    OptionCheckSyntax = true,
    OptionAutoCloseOnEnd = true
};
doc.LoadHtml(html);

string tdText = doc.DocumentNode.SelectSingleNode(".//td[@class='team_a_col home']")?.InnerText.Trim();

FixNestedTags 的结果是:0.89

【讨论】:

    【解决方案2】:

    你可以只取整行然后子字符串并获取数据吗?

    var node = doc.DocumentNode.SelectNodes("//htmlelment/htmlelment");
    
    string[] nodeArray = node[0].OuterHtml.Split(' ');
    

    【讨论】:

      猜你喜欢
      • 2011-12-08
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多