2012-02-20 50 views
0

我試着去下載一個網頁包含這樣如何通過html敏捷包分別獲取鏈接的標題和href值?

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

    <tr class="tt_row"> 

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

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

    </tr> 

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

表我想從TD類=「td_dl」提取TD類=「ttr_name」和下載鏈接name_of_the_movie

這是代碼我用來遍歷錶行

HtmlAgilityPack.HtmlDocument hDocument = new HtmlAgilityPack.HtmlDocument(); 
hDocument.LoadHtml(htmlSource); 
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]"); 
} 

目前我不知道如何檢查NameNode和linkNode和提取數據裏面

任何幫助,將不勝感激

問候

回答

3

我現在不能測試,但它應該是在電線之間的東西:

string name= namenode.Element("a").Element("b").InnerText; 
    string url= linknode.Element("a").GetAttributeValue("href","unknown"); 
1
nameNode.Attributes["title"] 
linkNode.Attributes["href"] 

假設你得到了正確的節點。

1
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); 
    } 

這裏是你如何提取所有href網址。我在我的一個項目中使用了這個正則表達式,您可以修改它以符合您的需求,並重寫它以匹配標題。我猜這是更方便的批量匹配他們