Get a value of an attribute by HtmlAgilityPack

后端 未结 5 1950
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 16:28

I want to get a value of an attribute by HtmlAgilityPack. Html code:





        
5条回答
  •  Happy的楠姐
    2020-12-17 17:26

    Following XPath selects link elements which have href attribute defined. Then from links you are selecting last one:

    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"
    

    You can also use last() XPath operator

    var link = doc.DocumentNode.SelectSingleNode("/link[@href][last()]");
    var href = link.Attributes["href"].Value;
    

    UPDATE: If you want to get last element which has both itemprop and href attributes, then use XPath //link[@href and @itemprop][last()] or //link[@href and @itemprop] if you'll go with first approach.

提交回复
热议问题