C# 如何使用htmlagilitypack提取div标记内的文本

C# 如何使用htmlagilitypack提取div标记内的文本,c#,html,winforms,html-agility-pack,C#,Html,Winforms,Html Agility Pack,我想在div类之间提取文本“sometext goes here”。 我正在使用html敏捷包和c# 我得到这个错误: An unhandled exception of type 'System.NullReferenceException' 如果文本是b/w a或而不是后代中的“div”,我知道如何提取,我必须给出“h1”或“p” 请有人帮忙。使用单引号,如 //div[@class='productDescriptionWrapper'] 要获取所有类型的所有子体,请使用: //div

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

我得到这个错误:

An unhandled exception of type 'System.NullReferenceException' 
如果文本是b/w a
而不是后代中的“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()]

如果
doc
是从您发布的HTML代码片段创建的,则无法获取空引用异常。无论如何,如果您想在外部
中获取文本,而不是从内部获取文本,那么请使用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);
…相比之下,以下内容返回所有文本:

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

[@class=\“productDescriptionWrapper\”
的右括号在哪里?可能是我在这里键入时遗漏了它…它不起作用。。
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);
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"