2015-05-04 87 views
0

我想提取div类之间的文本“Some text goes here”。 我使用的HTML敏捷包,和C#如何使用htmlagilitypack提取div标签内的文本

<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/wa <h1><p>,而不是后代中的“div”,我将不得不给出“h1”或“p”。

有人请协助。

+0

'[@class = \“productDescriptionWrapper \”''的右括号在哪里? – BCdotWEB

+0

可能是我错过了,当我在这里输入它时,它不工作.. – fizmhd

回答

1

使用单引号,如

//div[@class='productDescriptionWrapper']

让所有类型的所有后代使用:

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

得到特定类型 的后代,如p然后使用//div[@class='productDescriptionWrapper']//p

让那些无论是divp所有后代:

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

说你想获得的所有非空后代文本节点然后使用:

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

感谢它的工作原理... – fizmhd

1

没有办法,你可以获得空引用异常doc是从您发布的HTML代码段创建的。无论如何,如果你的意思是在外部<div>内获得文本,但不是从内部获得文本,则使用xpath /text()这意味着获得直接子文本节点

例如,给定此HTML片段:

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); 

..this仅从外<div>表达返回文本:在对比

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

..while,下面返回所有文本:

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