【问题标题】:Htmlagilitypack - Get all text + links inside of textHtmlagilitypack - 获取文本内的所有文本+链接
【发布时间】:2012-11-06 17:42:54
【问题描述】:

我有一种方法可以提取超过 XX 个单词的文本块。问题是它不会返回该文本内的链接。

我的方法:

public string getAllTextHTML(string _html)
{
  string _allText = "";
  try
  {
    HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
    document.LoadHtml(_html);

    document.DocumentNode.Descendants()
      .Where(n => n.Name == "script" || n.Name == "style")
      .ToList()
      .ForEach(n => n.Remove());

    RemoveComments(document.DocumentNode);

    var root = document.DocumentNode;
    var sb = new StringBuilder();
    foreach (var node in root.DescendantNodesAndSelf())
    {
      if (!node.HasChildNodes)
      {
        string text = node.InnerHtml;

        if (!string.IsNullOrEmpty(text))
        {
          int antalOrd = WordCounting.CountWords1(text);

          if (antalOrd > 25)
          {
            text = System.Web.HttpUtility.HtmlDecode(text);
            sb.AppendLine(text.Trim());
          }  
        } 
      }
    }

    _allText = sb.ToString();
  }
  catch (Exception)
  {
  }

  _allText = System.Web.HttpUtility.HtmlDecode(_allText);
  return _allText;
}

我怎样才能让这也让我获得文本中的链接?

【问题讨论】:

  • 我希望它可以在任何 html 页面上工作:/

标签: c# html-agility-pack


【解决方案1】:

我猜下面这行有问题:

if (!node.HasChildNodes)

因为,链接(锚点)是 htlm 标签,而您排除了带有子标签的 html 标签。

这是返回链接的简单示例:

String html = "<p>asdf<a href='#'>Test</a>asdfasd</p>";

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);

String p = (from x in doc.DocumentNode.Descendants()
            where x.Name == "p"
            select x.InnerHtml).FirstOrDefault();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2012-05-25
    • 2011-02-16
    • 2012-10-27
    • 1970-01-01
    相关资源
    最近更新 更多