NEWS

[C#] Hướng dẫn download tất cả image trên website về ổ đĩa local

[C#] Hướng dẫn download tất cả image trên website về ổ đĩa local
Đăng bởi: Thảo Meo - Lượt xem: 11386 10:54:43, 13/07/2017C#   In bài viết

Bài viết hôm nay, mình sẽ hướng dẫn các bạn cách download tất cả hình ảnh trên website C# về thư mục của bạn.

[C#] DOWNLOAD ALL IMAGE FROM URL WEBSITE CSHARP

Ví dụ: Nếu các bạn muốn download hình ảnh cả một website. Nhưng nhiều lúc website đó có quá nhiều hình ảnh, nếu chúng ta download thủ công thì sẽ mất rất nhiều thời gian.

Đây là link mình demo cho các bạn lấy hình ảnh về từ URL này:

 http://imgur.com/a/GPlx4

Giao diện website của link ở trên:

download all image csharp

- Cách download, mình sẽ sử dụng Webclient để download souce của url trên về.

- Tiếp tục chúng ta sẽ sử dụng Regular Expression trong .NET để lấy tất cả link của hình ảnh.

- Sau khi có link của hình ảnh, chúng ta sẽ load chúng về ổ đĩa của mình.

Source code download all image from website C#

WebClient wchtml = new WebClient();
string htmlString = wchtml.DownloadString("http://imgur.com/a/GPlx4");
int mastercount = 0;
Regex regPattern = new Regex(@"http://i.imgur.com/(.*?)alt=""", RegexOptions.Singleline);
MatchCollection matchImageLinks = regPattern.Matches(htmlString );
 
foreach (Match img_match in matchImageLinks)
{
    string imgurl = img_match.Groups[1].Value.ToString();
    Regex regx = new Regex("http://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?",
    RegexOptions.IgnoreCase);
    MatchCollection ms = regx.Matches(imgurl);
    foreach (Match m in ms)
    {
        Console.WriteLine("Downloading..  "  + m.Value);
        mastercount++;
        try
        {
            WebClient wc = new WebClient();
            wc.DownloadFile(m.Value, @"C:\_Imagesg_" + mastercount + ".gif");
            Thread.Sleep(1000);
        }
        catch (Exception x)
        {
            Console.WriteLine("Failed to download image.");
        }
        break;
    }
}

kết quả sau khi download:

download hinh anh tu website csharp

HAVE FUN :)

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn download tất cả image trên website về ổ đĩa local
Đăng bởi: Thảo Meo - Lượt xem: 11386 10:54:43, 13/07/2017C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.