我想在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 / wa <h1>
或<p>
而不是“div”,我將不得不提取“h1”或“p”。
有人請幫忙。
使用單引號,如
//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()]
如果從您發布的HTML片段創建doc
則無法獲得null引用異常。無論如何,如果你想在外部<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);
..這個表達式只返回外部<div>
文本:
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"