使用HtmlAgilityPack解析rel规范

时间:2012-11-19 12:37:12

标签: c# html-agility-pack

如何使用html文档中的URL解析rel =“canonical”标记?

我想在这里找到网址:

<link rel="canonical" href="http://stackoverflow.com/questions/2593147/html-agility-pack-make-code-look-neat" />

3 个答案:

答案 0 :(得分:3)

假设doc是您的HtmlDocument对象。

HtmlNodeCollection links = doc.DocumentNode.SelectNodes("//link[@rel]");

应该为您提供具有link属性的rel元素。现在迭代:

foreach (HtmlNode link in links)
{
    string url;
    if (link.Attributes["rel"] == "canonical") {
        url = link.Attributes["href"];
    }
}

此外,可以过滤SelectNodes调用中的链接,只获取具有“规范”的链接:doc.DocumentNode.SelectNodes("//link[@rel='canonical']");

没有经过测试的代码,但您明白了这一点:)

答案 1 :(得分:2)

接受的答案不再正确,更新后的代码如下:

var links = htmlDoc.DocumentNode.SelectNodes("//link[@rel]");

string canonical;

foreach (HtmlNode link in links)
{
    if (link.Attributes["rel"].Value == "canonical")
    {
        canonical = link.Attributes["href"].Value;
    }
}

答案 2 :(得分:0)

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(_html);

String link = (from x in doc.DocumentNode.Descendants()
           where x.Name == "link"
           && x.Attributes["rel"] != null
           && x.Attributes["rel"].Value == "canonical"
           && x.Attributes["href"] != null
           select x.Attributes["href"].Value).FirstOrDefault();
相关问题