65.9K
CodeProject 正在变化。 阅读更多。
Home

自动下载网站图片的应用程序

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.29/5 (3投票s)

2010年1月30日

CPOL

2分钟阅读

viewsIcon

27843

downloadIcon

1076

如果你看到一个有很多漂亮图片的网站,并且想把它们存储到你的电脑上,这个应用程序可以帮助你。

ImageDownloaderScreenShot.png

引言

有一个波士顿全球网站叫做“大图”(http://www.boston.com/bigpicture/),我很喜欢它。它展示了来自世界各地的人、动物、建筑物、事件以及各种各样其他正在发生的事情的照片。图片的质量非常出色,我经常用它们作为桌面背景。

我发现自己经常“另存为...”保存很多图片,需要一些东西来帮我完成这个任务。.NET框架使得做这样的事情变得非常容易,所以我花了几分钟时间编写了一个应用程序来自动下载图片。

注意:我将这些图片用作背景图片。请尊重摄影师的权利 - 不要将此应用程序用于任何非法目的。

解决方案

制作这样的应用程序非常简单。你需要做的是

  1. 获取指定页面的网站内容(HTML)
  2. 从HTML中获取图片URL
  3. 下载所有图片

所以…

  1. 我所做的是将一个WebBrowser组件添加到我的Windows窗体中,并启动Google。现在用户可以导航到他/她喜欢的任何页面。要获取当前文档的源代码,我使用WebBrowser.Document属性。
  2. 然后,我们使用以下方法从HTML中提取IMG标签
  3. public static List<string> GetImagesFromWebBrowserDocument(HtmlDocument document)
    {
        var result = new List<string>();
        // Get the <img> tags from the html
        foreach (HtmlElement item in document.Body.GetElementsByTagName("img"))
        {
            // Add the src attribute to the list - which contains the image url
            result.Add(item.GetAttribute("src"));
        }
        return result;
    }
  4. 最后,要下载图片,我使用WebClient
  5. public static void DownloadFile(string url,string destinationFolder)
    {
        if (!destinationFolder.EndsWith("\\"))
            destinationFolder = string.Concat(destinationFolder, "\\");
    
        using (var web = new WebClient())
        {
            var source = url;
            var segments = source.Split('/');
            // Get the filename of the image - and add
            // it after the destination folder address
            var destination = destinationFolder + 
                               segments[segments.Length - 1];
    
            try
            {
                // Download the file
                web.DownloadFile(source, destination);
                System.Diagnostics.Debug.WriteLine(string.Format(
                  "Download OK - {0} ==> {1}", source, destination));
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine(string.Format(
                  "Download FAILED - {0} ==> {1}", source, destination));
            }
        }
    }

我添加了选择下载文件夹的可能性,并添加了一些用于更新的事件,但这就是它的全部。

我未来可能想要做的事情

我可以添加一个图像最小尺寸的阈值,这样就不会每次都下载徽标等。此外,我没有对文件名(重复项)进行任何检查,但是嘿,它现在运行良好。

© . All rights reserved.