2011-01-29 63 views
7

我想使用HTML敏捷包來解析HTML頁面中的圖片和href鏈接,但我對XML或XPath知之甚少。儘管在許多網站上查找幫助文檔,但我無法解決問題。此外,我在VisualStudio 2005中使用C#,而且我不能流利地說英文,所以,我會衷心感謝能寫出一些有用的代碼。如何使用Html Agility Pack獲取img/src或a/hrefs?

+0

而且,可以Html敏捷包解決相對路徑? – iShow 2011-01-29 08:30:22

回答

21

主頁上的​​做一些非常相似,但考慮:

HtmlDocument doc = new HtmlDocument(); 
doc.Load("file.htm"); // would need doc.LoadHtml(htmlSource) if it is not a file 
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"]) 
{ 
    string href = link["href"].Value; 
    // store href somewhere 
} 

所以你可以想象,對於IMG SRC @,只需更換每個aimg,並且hrefsrc。 你甚至可以簡化爲:

foreach(HtmlNode node in doc.DocumentElement 
       .SelectNodes("//a/@href | //img/@src") 
{ 
    list.Add(node.Value); 
} 

相對URL處理,看看Uri類。

+0

非常感謝!這是我第一次詢問經驗 – iShow 2011-01-29 11:12:03

6

該示例和接受的答案是錯誤的。它不會用最新版本進行編譯。我嘗試別的:

private List<string> ParseLinks(string html) 
    { 
     var doc = new HtmlDocument(); 
     doc.LoadHtml(html); 
     var nodes = doc.DocumentNode.SelectNodes("//a[@href]"); 
     return nodes == null ? new List<string>() : nodes.ToList().ConvertAll(
       r => r.Attributes.ToList().ConvertAll(
       i => i.Value)).SelectMany(j => j).ToList(); 
    } 

這對我有用。

1

也許我太遲了,在這裏發表一個答案。以下爲我工作:

var MainImageString = MainImageNode.Attributes.Where(i=> i.Name=="src").FirstOrDefault(); 
相關問題