2020-09-06 C#模拟浏览器批量按规则抓取图片或文件并按路径保存

C#模拟浏览器批量按规则抓取图片或文件并按路径保存。

本身是为了抓取地图网站的分块图数据,网上找了一圈没有好的代码实现,那就只好自己动手写一个,代码比较简单,就不写注释了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ApplicationTools
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 27425; i < 27440; i++)
            {
                for (int j = 13386; j < 13395; j++)
                {
                    System.Drawing.Image img = ImgGet(i, j);
                    ImgSave(img, i, j);
                    Thread.Sleep(2000);
                }
            }
        }


        public static System.Drawing.Image ImgGet(int path, int filename)
        {
            string url = string.Format("http://www.test.com/{0}/{1}.png", path, filename);
            
            HttpWebRequest imgRequest = WebRequest.Create(url) as HttpWebRequest;

            imgRequest.Accept = "text/html, application/xhtml+xml, image/jxr, */*";
            imgRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586";
            imgRequest.Method = "GET";
            imgRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
            imgRequest.Headers.Add("Accept-Language", "zh-CN");
            HttpWebResponse res;
            try
            {
                res = (HttpWebResponse)imgRequest.GetResponse();
            }
            catch (WebException ex)
            {

                res = (HttpWebResponse)ex.Response;
            }


            if (res.StatusCode.ToString() == "OK")
            {
                System.Drawing.Image downImage = System.Drawing.Image.FromStream(imgRequest.GetResponse().GetResponseStream());
                return downImage;
            }
            else
            {
                return null;
            }

        }


        public static void ImgSave(System.Drawing.Image downImage, int path, int filename)
        {
            if (downImage != null)
            {
                string directorypath = string.Format(@"D:\Temp\images\15\{0}\", path);

                string fileName = string.Format("{0}.png", filename);


                if (!System.IO.Directory.Exists(directorypath))
                {
                    System.IO.Directory.CreateDirectory(directorypath);
                }
                downImage.Save(directorypath + fileName);
                downImage.Dispose();
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值