2010-01-21 16 views
16

我剛剛下載了HTMLAgilityPack,並且文檔沒有任何示例。如何使用HTML敏捷性包檢索網站中的所有圖像?

我正在尋找一種方式從網站下載所有圖像。地址字符串,而不是物理圖像。

<img src="blabalbalbal.jpeg" /> 

我需要拉每個img標籤的來源。我只想感受一下圖書館和它可以提供什麼。大家都說這是這個工作最好的工具。

編輯

public void GetAllImages() 
    { 
     WebClient x = new WebClient(); 
     string source = x.DownloadString(@"http://www.google.com"); 

     HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); 
     document.Load(source); 

         //I can't use the Descendants method. It doesn't appear. 
     var ImageURLS = document.desc 
        .Select(e => e.GetAttributeValue("src", null)) 
        .Where(s => !String.IsNullOrEmpty(s));   
    } 

回答

32

你可以做到這一點使用LINQ,像這樣:

var document = new HtmlWeb().Load(url); 
var urls = document.DocumentNode.Descendants("img") 
           .Select(e => e.GetAttributeValue("src", null)) 
           .Where(s => !String.IsNullOrEmpty(s)); 

編輯:現在這個代碼實際工作;我忘了寫document.DocumentNode。基於

+0

什麼對象類型是文件在你的榜樣?我無法使用.Descendants方法。請檢查我的編輯。 – 2010-01-22 00:01:00

+0

我忘了加入'.DocumentNode'。 – SLaks 2010-01-22 00:09:21

+0

也檢查你使用的是最新的測試版,因爲linq功能是新的 – rtpHarry 2010-04-06 23:06:02

7

自己的一個例子,但修改的XPath:

HtmlDocument doc = new HtmlDocument(); 
List<string> image_links = new List<string>(); 
doc.Load("file.htm"); 
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//img")) 
{ 
    image_links.Add(link.GetAttributeValue("src", "")); 
} 

我不知道這個擴展,所以我不知道怎麼寫出來的陣列到別的地方,但將在最少讓你的數據。 (另外,我沒有正確定義陣列,我敢肯定,對不起)。

編輯

使用你的例子:

public void GetAllImages() 
    { 
     WebClient x = new WebClient(); 
     string source = x.DownloadString(@"http://www.google.com"); 

     HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument(); 
     List<string> image_links = new List<string>(); 
     document.Load(source); 

     foreach(HtmlNode link in document.DocumentElement.SelectNodes("//img")) 
     { 
      image_links.Add(link.GetAttributeValue("src", "")); 
     } 


    } 
+0

做到這一點:'列表 image_links =新列表(); image_links.Add(link.GetAttributeValue(「src」,「」)); }' – TaW 2015-02-23 09:58:34