Je veux obtenir une valeur d'un attribut par HtmlAgilityPack. Code HTML:
<link href="style.css">
<link href="anotherstyle.css">
<link href="anotherstyle2.css">
<link itemprop="thumbnailUrl" href="http://image.jpg">
<link href="anotherstyle5.css">
<link href="anotherstyle7.css">
Je veux obtenir le dernier attribut href.
Mon code c #:
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument htmldoc = web.Load(Url);
htmldoc.OptionFixNestedTags = true;
var navigator = (HtmlNodeNavigator)htmldoc.CreateNavigator();
string xpath = "//link/@href";
string val = navigator.SelectSingleNode(xpath).Value;
Mais ce code retourne la première valeur href.
Après XPath, sélectionne les éléments de link
lesquels l'attribut href
défini. Ensuite, à partir des liens que vous sélectionnez en dernier:
var link = doc.DocumentNode.SelectNodes("//link[@href]").LastOrDefault();
// you can also check if link is not null
var href = link.Attributes["href"].Value; // "anotherstyle7.css"
Vous pouvez également utiliser last()
opérateur last()
XPath
var link = doc.DocumentNode.SelectSingleNode("/link[@href][last()]");
var href = link.Attributes["href"].Value;
UPDATE: Si vous voulez obtenir le dernier élément avec les itemprop
et href
, utilisez XPath //link[@href and @itemprop][last()]
ou //link[@href and @itemprop]
aller avec première approche.