<html>
<body>
<div class="main">
<div class="submain"><h2></h2><p></p><ul></ul>
</div>
<div class="submain"><h2></h2><p></p><ul></ul>
</div>
</div>
</body>
</html>
Ich habe den HTML- HtmlDocument
in ein HtmlDocument
. Dann habe ich den XPath als submain
. Dann weiß ich nicht, wie man zu einzelnen Tags dh h2
, p
getrennt h2
.
HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class=\"submain\"]");
foreach (HtmlAgilityPack.HtmlNode node in nodes) {}
Wenn ich node.InnerText
verwende node.InnerText
ich alle Texte und InnerHtml
ist auch nicht sinnvoll. Wie wähle ich einzelne Tags aus?
Folgendes wird helfen:
HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class=\"submain\"]");
foreach (HtmlAgilityPack.HtmlNode node in nodes) {
//Do you say you want to access to <h2>, <p> here?
//You can do:
HtmlNode h2Node = node.SelectSingleNode("./h2"); //That will get the first <h2> node
HtmlNode allH2Nodes= node.SelectNodes(".//h2"); //That will search in depth too
//And you can also take a look at the children, without using XPath (like in a tree):
HtmlNode h2Node = node.ChildNodes["h2"];
}
Sie suchen Nachkommen
var firstSubmainNodeName = doc
.DocumentNode
.Descendants()
.Where(n => n.Attributes["class"].Value == "submain")
.First()
.InnerText;