나는 "div"에서 텍스트를 가져 와서 다른 모든 것을 제외하려고합니다. 도와 줄수있으세요 ?!
<div class="article">
<div class="date">01.01.2000</div>
<div class="news-type"><a href="../link/page01">Breaking News</a></div>
"Here is the location of the text i would like to pull"
</div>
"article"클래스를 가져 오면 모든 것을 얻을 수 있지만 class = "date", class = "news-type"및 그 안에있는 모든 것을 제외하는 방법을 알 수 없습니다.
다음은 내가 사용하는 코드입니다.
HtmlDocument doc = web.Load(url);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[contains(@class,'article')]"))
{
name_text.text += node.InnerHtml.Trim();
}
고맙습니다!
또 다른 방법은 div
요소에서 비어 있지 않은 직접 자식 텍스트 노드를 얻기 위해 XPath /text()[normalize-space()]
를 사용하는 것입니다.
var divs = doc.DocumentNode.SelectNodes("//div[contains(@class,'article')]");
foreach (HtmlNode div in divs)
{
var node = div.SelectSingleNode("text()[normalize-space()]");
Console.WriteLine(node.InnerText.Trim());
}
출력 :
"Here is the location of the text i would like to pull"
HtmlTextNode 유형 인 ChildNodes를 원한다. 테스트되지 않은 추천 코드 :
var textNodes = node.ChildNodes.OfType<HtmlTextNode>();
if (textNodes.Any())
{
name_text.text += string.Join(string.Empty, textNodes.Select(tn => tn.InnerHtml));
}