如何根据此页面上的链接从网页下载图片?

时间:2012-11-07 16:14:23

标签: c# .net image web download

这是我到目前为止所遇到的问题,但我遇到了一个问题。

页面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);
            }
        }
    }

这个问题发生在这里。由于某种原因,对象“path”始终为null。因此我无法下载图片。

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(页面上的图片的一个链接)。

1 个答案:

答案 0 :(得分:0)

请勿尝试自行解析文档。查看HTML Agility Pack(http://htmlagilitypack.codeplex.com/)以从HTML文档中提取有意义的信息。