我想在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"