通过HtmlAgilityPack获取属性的值 [英] Get a value of an attribute by HtmlAgilityPack

查看:108
本文介绍了通过HtmlAgilityPack获取属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过HtmlAgilityPack获取属性值. HTML代码:

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

<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">

我想获取最后一个href属性.

I want to get last href attribute.

我的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;

但是该代码返回第一个href值.

But that code return first href value.

推荐答案

在XPath之后,选择定义了href属性的link元素.然后从链接中选择最后一个:

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"

您还可以使用last() XPath运算符

You can also use last() XPath operator

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

更新:如果要获取同时具有itemprophref属性的最后一个元素,请使用XPath //link[@href and @itemprop][last()]//link[@href and @itemprop](如果您要采用第一种方法).

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.

这篇关于通过HtmlAgilityPack获取属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆