11

我正在尝试使用 HTML Agility Pack 从以下内容中获取描述文本:

<meta name="description" content="**this is the text i want to extract and store in a string**" />

不久前 Stackoverflow 上的某个人建议我使用 HTMLAgilityPack。但是我不知道如何使用它,并且我找到的它的文档(包括下载中包含的文档)都有无效链接,因此无法查看文档。

有人可以帮我解决这个问题吗?

4

2 回答 2

18

XmlDocument用法与;非常相似 您可以使用 MSDNXmlDocument进行广泛的概述;您可能还想学习 xpath 语法 ( MSDN )。

例子:

HtmlDocument doc = new HtmlDocument();
doc.Load(path); // or .LoadHtml(html);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//meta[@name='description']");
if (node != null) {
    string desc = node.GetAttributeValue("content", "");
    // TODO: write desc somewhere
}

的第二个参数GetAttributeValue是在未找到该属性的情况下返回的默认值。

于 2009-12-10T22:16:17.473 回答
0

公共字符串 HtmlAgi(字符串 url,字符串键){

    var Webget = new HtmlWeb();
    var doc = Webget.Load(url);
    HtmlNode ourNode = doc.DocumentNode.SelectSingleNode(string.Format("//meta[@name='{0}']", key));

    if (ourNode != null)
    {


            return ourNode.GetAttributeValue("content", "");

    }
    else
    {
        return "not fount";
    }

}
于 2014-03-27T16:00:19.050 回答