2016-03-15 59 views
1

我開始使用Anglesharp作爲項目,我需要獲取並下載的不僅僅是HTML,還需要下載文檔的圖像。 我知道在Document對象中有一個名爲Images的屬性,但顯然它沒有得到它們,我在YouTube頁面上做了一個測試,並且只有一個(重複了幾次)。 例如,我想獲取當前視頻的縮略圖,而且這似乎在<meta>標記內。 爲了更準確,圖像存儲這樣的標籤裏面:使用AngleSharp獲取並下載圖片

<meta content="https://i.ytimg.com/vi/hW-kDv1WcQM/hqdefault.jpg" property="og:image"> 

所以我想如果有一種方法來選擇所有節點/頁,不管使用的標籤內的任何圖像的URL。 我不認爲QuerySelectorAll在這種情況下工作,因爲它只選擇一種類型的節點。 你可以試試你在github上,以驗證發現的示例代碼(我只是改變了URL與YouTube的一個,並且選擇太:d):

// Setup the configuration to support document loading 
var config = Configuration.Default.WithDefaultLoader(); 
// Load the names of all The Big Bang Theory episodes from Wikipedia 
var address = "https://www.youtube.com/watch?v=hW-kDv1WcQM&feature=youtu.be"; 
// Asynchronously get the document in a new context using the configuration 
var document = await BrowsingContext.New(config).OpenAsync(address); 
// This CSS selector gets the desired content 
var cellSelector = "img"; 
// Perform the query to get all cells with the content 
var cells = document.QuerySelectorAll(cellSelector); 
// We are only interested in the text - select it with LINQ 
var titles = cells.Select(m => m.TextContent); 

哦,舒爾,你還可以添加這檢查圖像屬性是否沒有得到視頻縮略圖:

var Images = document.Images.Select(sl=> sl.Source).Distinct().ToList(); 

其他任何基於URL內容選擇節點的方法? (像所有以「.jpg」或「巴紐」等結束的網址)

+0

請提供證據表明你已經完成了一些研究(即你認爲可能幫助你的鏈接但不確定) – MikeDub

+0

我做了,但是Anglesharp沒有很多文檔(如果在這裏尋找Anglesharp標籤stackexchage你得到像17(包括我的)結果:http://stackoverflow.com/questions/tagged/anglesharp)。 谷歌搜索也沒有幫助,你可以嘗試幾個搜索詞,但AngleShapr沒有太多。 – Toshiwo

回答

3

您可以使用LINQ API來獲取包含頁圖像的URL的所有屬性,就像這樣:

..... 
var document = await BrowsingContext.New(config).OpenAsync(address); 

//list all image file extension here : 
var fileExtensions = new string[] { ".jpg", ".png" }; 

//find all attribute in any element... 
//where the value ends with one of the listed file extension      
var result = from element in document.All 
      from attribute in element.Attributes 
      where fileExtensions.Any(e => attribute.Value.EndsWith(e)) 
      select attribute; 

foreach (var item in result) 
{ 
    Console.WriteLine(item.Value); 
}