下载网站的所有图像

时间:2014-10-04 02:10:40

标签: c# webclient

所以我昨晚刚开始学习C#。我开始的第一个项目是一个简单的Image-Downloader,它使用HtmlElementCollection下载网站的所有图像。

这是我到目前为止所得到的:

    private void dl_Click(object sender, EventArgs e)
    {
        System.Net.WebClient wClient = new System.Net.WebClient();

        HtmlElementCollection hecImages = Browser.Document.GetElementsByTagName("img");

        for (int i = 0; i < hecImages.Count - 1; i++)
        {

            char[] ftype = new char[4];
            string gtype;

            try
            {
                //filetype
                hecImages[i].GetAttribute("src").CopyTo(hecImages[i].GetAttribute("src").Length -4,ftype,0,4) ;
                gtype = new string(ftype);

                //copy image to local path
                wClient.DownloadFile(hecImages[i].GetAttribute("src"), absPath + i.ToString() + gtype);                                                                               
            }
            catch (System.Net.WebException) 
            {
                expand_Exception_Log();
                System.Threading.Thread.Sleep(50);
            }

基本上它是提前渲染页面并寻找图像。这很好用,但由于某种原因它只下载缩略图,而不是完整(高分辨率)图像。

其他来源:

WebClient.DownloadFile上的文档:http://msdn.microsoft.com/en-us/library/ez801hhe(v=vs.110).aspx

  

DownloadFile方法从地址参数中指定的URI下载到本地文件数据。

1 个答案:

答案 0 :(得分:5)

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

为例

这使用名为HTML Agility Pack的库来下载网站上的所有<img src="" \>行。 How can I use HTML Agility Pack to retrieve all the images from a website?

如果该主题以某种方式消失,我会为那些需要它但却无法达到该主题的人提出这个主题。

// Creating a list array
public List<string> ImageList; 
public void GetAllImages()
{
    // Declaring 'x' as a new WebClient() method
    WebClient x = new WebClient();

    // Setting the URL, then downloading the data from the URL.
    string source = x.DownloadString(@"http://www.google.com");

    // Declaring 'document' as new HtmlAgilityPack() method
    HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();

    // Loading document's source via HtmlAgilityPack
    document.LoadHtml(source);

    // For every tag in the HTML containing the node img.
    foreach(var link in document.DocumentNode.Descendants("img")
                                .Select(i => i.Attributes["src"])) 
    {
        // Storing all links found in an array.
        // You can declare this however you want.
        ImageList.Add(link.Attribute["src"].Value.ToString());
    }
}

由于您的说法很新,所以您可以使用NuGet轻松添加HTML Agility Pack。 要在项目中添加right-click,请点击Manage NuGet Packages,在左侧的“在线”标签中搜索HTML Agility Pack,然后点击“安装”。您需要使用using HtmlAgilityPack;

来调用它

毕竟,您应该可以创建并使用已创建的方法来下载上面创建的image_list数组中包含的所有项目。

祝你好运!

编辑: 添加了解释每个部分内容的评论。

EDIT2: 更新后的摘录以反映用户评论。

相关问题