2015-12-02 48 views
0

我正在嘗試獲取圖片的Url,目前我有這樣的代碼可以工作,但需要webBrowser才能這樣做。獲取沒有瀏覽器的文件url-C#

public void getFileUrl(HtmlDocument htmlDocument) 
    { 
     HtmlElementCollection htmlCollectionImage = htmlDocument.Images; 
     foreach (HtmlElement htmlImage in htmlCollectionImage) 
     { 
      string Url = htmlImage.GetAttribute("src"); 
      if (Url.StartsWith("http://www.exemple.com/")) 
      { 
       MessageBox.Show(Url); 
      } 
     } 
    } 

我需要和平的事情,不需要webBrowser,但我真的不知道該怎麼做。

而不是一個HtmlDocument htmlDocument被送入該方法,我需要餵它一個簡單的string

還可以嗎?

+1

可能的重複[從網站C#獲取HTML代碼](http://stackoverflow.com/questions/16642196/get-html-code-from-a-website-c-sharp) – Sievajet

回答

0

嘗試這樣:

static void Main() 
{ 
    var fileUrls = GetFileUrl(@"https://stackoverflow.com/questions/34054662/get-a-file-url-without-webbrowser-c-sharp", @"https://www.gravatar.com/"); 

    foreach (string url in fileUrls) 
    { 
     Console.WriteLine(url); 
    } 

    Console.ReadKey(); 
} 

public static IEnumerable<string> GetFileUrls(string url) 
{ 
    var document = new HtmlWeb().Load(url); 
    var urls = document.DocumentNode.Descendants("img") 
            .Select(e => e.GetAttributeValue("src", null)) 
            .Where(s => s.ToLower().StartsWith(pattern)); 

    return urls; 
} 

摘自:How can I use HTML Agility Pack to retrieve all the images from a website?

編輯,包括使用和模式參數添加到GetFileUrls()。

+0

我試過了什麼你建議,但我當我嘗試檢查返回的'urls.ToString()',我得到這個:'System.Linq.Enumerable + WhereEnumerableIterator 1 [System.String]' 我試圖使用URL並仍然沒有'工作。我不知道我是否做錯了 –

+0

我編輯了我的答案以顯示如何使用它。由於它返回的是圖像集合('IEnumerable '),因此不能將其轉換爲字符串。你需要遍歷它,然後你可以使用每個url。我還編輯了添加第二個參數pattern的方法,以便您可以在調用方法時指定要啓動的方法 - 請小心使用http/https,因爲它可能會給您帶來一些麻煩,也許可以考慮將其更改爲string.Contains()並省略協議,甚至RegEx。 – tom982

+0

感謝得到它的工作,我的問題是我試圖從'GetFileUrls()'裏面檢查'urls',而不是像'url'那樣檢查。 –