2015-05-04 86 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" 
相關問題