With html agility pack, how can I retrieve the title and href value of a link separately?

.net c# html-agility-pack


Im trying to download a page contain a table like this

<table id="content-table">
      <th id="name">Name</th>
      <th id="link">link</th>

    <tr class="tt_row">

      <td class="ttr_name">
       <a title="name_of_the_movie" href="#"><b>name_of_the_movie</b></a>
       <span class="pre">message</span>

      <td class="td_dl">
        <a href="download_link"><img alt="Download" src="#"></a>


    <tr class="tt_row"> .... </tr>
    <tr class="tt_row"> .... </tr>

i want to extract the name_of_the_movie from td class="ttr_name" and download link from td class="td_dl"

this is the code i used to loop through table rows

HtmlAgilityPack.HtmlDocument hDocument = new HtmlAgilityPack.HtmlDocument();
HtmlNode table = hDocument.DocumentNode.SelectSingleNode("//table");

foreach (var row in table.SelectNodes("//tr"))
  HtmlNode nameNode = row.SelectSingleNode("td[0]");
  HtmlNode linkNode = row.SelectSingleNode("td[1]");

currently i have no idea how to check the nameNode and linkNode and extract data inside it

any help would be appreciated


2/20/2012 8:36:10 AM

Accepted Answer

I can't test it right now, but it should be something among the lines of :

    string name= namenode.Element("a").Element("b").InnerText;
    string url= linknode.Element("a").GetAttributeValue("href","unknown");
2/20/2012 9:03:53 AM

Popular Answer

    public const string UrlExtractor = @"(?: href\s*=)(?:[\s""']*)(?!#|mailto|location.|javascript|.*css|.*this\.)(?<url>.*?)(?:[\s>""'])";

    public static Match GetMatchRegEx(string text)
        return new Regex(UrlExtractor, RegexOptions.IgnoreCase).Match(text);

Here is how you can extract all Href Url. I'm using that regex in one of my projects, you can modify it to match your needs and rewrite it to match title as well. I guess it is more convenient to match them in bulk

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow