11
votes

I'm trying to use HTML Agility Pack to get the description text from inside the:

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

And someone on Stackoverflow a little while ago suggested I use HTMLAgilityPack. But I don't know how to use it, and the documentation for it that I've found (including the docs contained in the downloads) all have invalid links and therefor cannot view the documentation.

Can somebody please help me solve this?

2
I'm confused - have you built HtmlAgilityPack or not? Is it the examples that don't build? or the core dll? If the latter, what have you referenced? - Marc Gravell
thanks Marc. I've edited my question and removed that part to avoid further confusion. Thinking about it now, that specific part wasn't really relative to my question, rather abit of info to say why i'm asking the question. - jay_t55
i have been able to add a reference in my app to the dll file. so i can "use" htmlagility pack. - jay_t55
Just for reference (since this question appears as the first Google result for the GetAttributeValue method), the second argument is the default value to return in case the attribute is not found. Here's the complete definition of the method: /// <summary> /// Helper method to get the value of an attribute of this node. If the attribute is not found, the default value will be returned. /// </summary> /// <param name="name">The name of the attribute to get. May not be <c>null</c>.</param> /// <param name="def">The default value to return if not found.</param> /// <returns>The value of the att - alf

2 Answers

18
votes

The usage is very similar to XmlDocument; you could use MSDN on XmlDocument for a broad overview; you might also want to learn xpath syntax (MSDN).

Example:

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
}

The second argument to GetAttributeValue is the default returned in case the attribute is not found.

0
votes

public string HtmlAgi(string url, string key) {

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

}