私は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」の代わりに「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"