<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>
J'ai chargé le HtmlDocument
HTML dans un document HtmlDocument
. Ensuite, j'ai sélectionné le XPath en tant que sous- submain
. Ensuite, je ne sais pas comment accéder à chaque balise, à savoir h2
, p
séparément.
HtmlAgilityPack.HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class=\"submain\"]");
foreach (HtmlAgilityPack.HtmlNode node in nodes) {}
Si j'utilise node.InnerText
je reçois tous les textes et InnerHtml
n'est également pas utile. Comment sélectionner des tags séparés?
Ce qui suit aidera:
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"];
}
Vous recherchez des descendants
var firstSubmainNodeName = doc
.DocumentNode
.Descendants()
.Where(n => n.Attributes["class"].Value == "submain")
.First()
.InnerText;