【问题标题】:How to extract text inside a div tag using htmlagilitypack如何使用 htmlagilitypack 提取 div 标签内的文本
【发布时间】:2015-05-04 14:50:27
【问题描述】:

我想在 div 类之间提取文本“Some text goes here”。 我正在使用 html 敏捷包和 c#

<div class="productDescriptionWrapper">
Some Text Goes here...
<div class="emptyClear"> </div>
</div>

这就是我所拥有的:

Description = doc.DocumentNode.SelectNodes("//div[@class=\"productDescriptionWrapper\").Descendants("div").Select(x => x.InnerText).ToList();

我收到此错误:

An unhandled exception of type 'System.NullReferenceException' 

如果文本是 b/w &lt;h1&gt; 或 &lt;p&gt; 而不是后代中的“div”,我知道如何提取,我将不得不给出“h1”或“p”。

请有人帮忙。

【问题讨论】:

  • [@class=\"productDescriptionWrapper\" 的右括号在哪里?
  • 可能是我在这里输入时错过了它...它不起作用..

标签: c# html winforms html-agility-pack


【解决方案1】:

使用单引号,如

//div[@class='productDescriptionWrapper']

要获取所有类型的所有后代,请使用:

//div[@class='productDescriptionWrapper']//*,

获取特定类型的所有后代 比如p,然后使用//div[@class='productDescriptionWrapper']//p。

获取div 或p 的所有后代:

//div[@class='productDescriptionWrapper']//*[self::div or self::p] 

假设您想获取所有非空白后代文本节点,然后使用:

//div[@class='productDescriptionWrapper']//text()[normalize-space()]

【讨论】:

    【解决方案2】:

    鉴于doc 是从您发布的HTML sn-p 创建的,您无法获得空引用异常。无论如何,如果您打算在外部 &lt;div&gt; 中获取文本,而不是从内部获取文本,那么请使用 xpath /text(),这意味着 获取直接子文本节点。

    例如,给定这个 HTML sn-p :

    var html = @"<div class=""productDescriptionWrapper"">
    Some Text Goes here...
    <div class=""emptyClear"">Don't get this one</div>
    </div>";
    var doc = new HtmlDocument();
    doc.LoadHtml(html);
    

    ..此表达式仅从外部 &lt;div&gt; 返回文本:

    var Description = doc.DocumentNode
                         .SelectNodes("//div[@class='productDescriptionWrapper']/text()")
                         .Select(x => x.InnerText.Trim())
                         .First();
    //Description : 
    //"Some Text Goes here..."
    

    ..而相比之下,以下返回所有文本:

    var Description = doc.DocumentNode
                         .SelectNodes("//div[@class='productDescriptionWrapper']")
                         .Select(x => x.InnerText.Trim())
                         .First();
    //Description :
    //"Some Text Goes here...
    //Don't get this one"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多