c# - 如何根据该页面上的链接从网页下载图片?

标签 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);
            }
        }
    }

问题发生在这里。由于某种原因,对象“路径”始终为空。所以我无法下载图片。

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

最佳答案

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

关于c# - 如何根据该页面上的链接从网页下载图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13273697/

相关文章:

linux - 创建 iso,可使用命令 'dd' 安装

java - 将图像转换为按钮数组

c# - 调试 C++/Cli : <Unknown function> and no Locals

android - 如何在android中以html格式的电子邮件发送图像?

c# - Entity Framework 核心一对多

c# - 为什么需要在客户端项目中引用 EntityFramework.dll 来使 DbContext IDisposable?

javascript - 以优雅的方式将响应文本解析为键值对

c# - CodeDom 添加对现有文件的引用

c# - 更改 HttpWebRequest 实例的 Uri?

c# - 如何将 QueueUserWorkItem 与 ref/out 状态一起使用?