【问题标题】:Html Agility Pack get specific content from a divHtml Agility Pack 从 div 获取特定内容
【发布时间】:2016-09-25 13:42:15
【问题描述】:

我正在尝试从“div”中提取文本并排除其他所有内容。你能帮帮我吗?!

<div class="article">
   <div class="date">01.01.2000</div>
   <div class="news-type"><a href="../link/page01">Breaking News</a></div>

   "Here is the location of the text i would like to pull"

</div>

当我提取“文章”类时,我得到了所有内容,但我无法/不知道如何排除 class="date"、class="news-type" 以及其中的所有内容。

这是我使用的代码:

HtmlDocument doc = web.Load(url);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[contains(@class,'article')]"))
{
    name_text.text += node.InnerHtml.Trim();
}

谢谢!

【问题讨论】:

    标签: c# html html-agility-pack


    【解决方案1】:

    另一种方法是使用 XPath /text()[normalize-space()]div 元素中获取 非空 直接子文本节点:

    var divs = doc.DocumentNode.SelectNodes("//div[contains(@class,'article')]");
    foreach (HtmlNode div in divs)
    {
        var node = div.SelectSingleNode("text()[normalize-space()]");
        Console.WriteLine(node.InnerText.Trim());
    }
    

    dotnetfiddle demo

    输出:

    "Here is the location of the text i would like to pull"
    

    【讨论】:

    • 非常感谢您对我的帮助。如果我可以再问一个问题。如果我有多个
      ?我怎样才能把它们全部列出来?循环会是什么样子?谢谢。
    【解决方案2】:

    您需要 HtmlTextNode 类型的 ChildNode。未经测试的建议代码:

    var textNodes = node.ChildNodes.OfType<HtmlTextNode>();
    if (textNodes.Any())
    {
        name_text.text += string.Join(string.Empty, textNodes.Select(tn => tn.InnerHtml));
    }
    

    【讨论】:

    • 非常感谢您对我的帮助。
    猜你喜欢
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 2011-10-13
    • 1970-01-01
    相关资源
    最近更新 更多