2012-11-07 73 views
2

這是我到目前爲止,但我遇到了一個問題。如何根據網頁上的鏈接從網頁下載圖片?

頁面https://xxxxxxxx.zendesk.com/tickets/33126包含指向.jpg圖像的鏈接。我想下載這張圖片。所以我需要掃描的頁面找到所有的個.jpg,.gif等

I'm having an issue with my code at the end. I'll explain there. 

    public static void GetTicketAttachments(string url) 
    { 
     GetImages("https://xxxxxxxx.zendesk.com/tickets/33126"); 
    } 

static void GetImages(string url) 
    { 
     string responseString; 
     HttpWebRequest initialRequest = (HttpWebRequest)WebRequest.Create(url); 
     using (HttpWebResponse initialResponse = (HttpWebResponse)initialRequest.GetResponse()) 
     { 
      using (StreamReader reader = new StreamReader(initialResponse.GetResponseStream())) 
      { 
       responseString = reader.ReadToEnd(); 
      } 

      List<string> imageset = new List<string>(); 
      Regex regex = new Regex(@"f=""[^""]*jpg|bmp|tif|gif|png", RegexOptions.IgnoreCase); 
      foreach (Match m in regex.Matches(responseString)) 
      { 
       if (!imageset.Contains(m.Value)) 
        imageset.Add(m.Value); 
      } 
      for (int i = 0; i < imageset.Count; i++) 
       imageset[i] = imageset[i].Remove(0, 3); 
      totalFiles = imageset.Count; 
      currentFiles = totalFiles; 

      foreach (string f in imageset) 
      { 
       ThreadPool.QueueUserWorkItem(new WaitCallback(DownloadImage), f); 
      } 
     } 
    } 

問題發生在這裏的頁面可能有多個圖像。出於某種原因,對象「路徑」始終爲空。因此我無法下載圖片。

static void DownloadImage(object path) 
    { 
     currentFiles--; 
     path = Path.GetFileName(path.ToString()); 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(path.ToString()); 
     using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
     { 
      Image image = Image.FromStream(response.GetResponseStream()); 
      image.Save(@"C:\" + Path.GetFileName(path.ToString())); 
     } 
    } 

任何人都知道可能是什麼問題? 「圖片計數」實際上正在計數1(鏈接到頁面上的一張圖片)。

+0

此外,你可能遇到了一個線程問題,'f'的值沒有被正確關閉。你需要一個foreach循環的內部變量。 – Tejs

+0

是f null?另外,如果鏈接是相對的,你需要使它們成爲絕對的。 – bmm6o

+0

@ bmm6o,是F爲空。出於某種原因,我在響應字符串中看不到任何.jpg。 –

回答