C#爬取目标网址的图片
hello,大家好。我是闲齁齁,一枚用发量写代码的程序员。由于这段时间进厂进修(摸鱼)导致有一段时间没有更新博客,今天主要写的是使用C#爬取目标网址的图片,也就是爬虫。大家都知道绝大部分的爬虫都是使用Python来写的,但这并不代表别的语言不能写。所以作为一名C#程序员,今天用C#搞了一个简单的小爬虫。
其实稍微简单的爬虫就分那么几步,当然高深的我写不出来(我是不会告诉你们我写不出来的)。
- HTTP的请求与响应
- 网页流的获取
- 根据分析得到相关资源
- 下载并进行整理
首先说第一步HTTP的请求与响应,在C#里有好几个类可以实现:“WebClient,WebRequest,WebRespond,HttpWebRequest”具体类的功能可以查询文档。第二步就是获取网页流并读取,第三步是根据分析得到相关资源,比如正则表达式,获取使用一些抓包工具的解析得到你所需要的,我在这使用的是正则表达式。第四步就是下载并整理,WebClien类的DownloadFile等方法可以下载。
WebClien的具体使用
接下来就到了实现功能环节:
#region 爬取图片代码
public static void HttpGetHandle(string url,string path, int name)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.CreateHttp(url);
webRequest.Method = "GET";
webRequest.UserAgent = " Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0";
var webResponse = webRequest.GetResponse();
StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.ASCII);
string str = streamReader.ReadToEnd();
streamReader.Close();
if (string.IsNullOrEmpty(str))
{
Console.WriteLine("————————-错误—————————");
Console.ReadKey();
}
Regex regex = new Regex(@"ess-data='(.*?)'>");
MatchCollection match = regex.Matches(str);
WebClient client = new WebClient();
int temp = 0;
try
{
foreach (Match match1 in match)
{
string src = match1.Groups[1].Value;
if (src.Contains("http") && !src.Contains(".svg"))
{
temp++;
client.DownloadFile(src, path + name + ".jpg");
name++;
Console.WriteLine("\n正在爬取——图片下载地址" + "|" + src + "|" + temp);
}
}
}
catch (Exception ex)
{
Console.WriteLine("-------------" + ex);
}
stopwatch.Stop();
Console.WriteLine("————-———爬取成功!—————");
Console.WriteLine("\n_______总共爬取了" + temp + "张图片!_______________");
Console.WriteLine("\n一共耗时" + stopwatch.ElapsedMilliseconds / 1000 + "秒");
}
#endregion
#region 创建一个储存图片的文件夹
public static void CreatFile(string path)
{
if (Directory.Exists(path))
{
Console.WriteLine("\n————————开始——————————");
}
else
{
DirectoryInfo directory = new DirectoryInfo(path);
directory.Create();
}
}
#endregion
这两个方法被我单独写了一个类,接下来就是主函数的直接调用了。
static void Main(string[] args)
{
Console.WriteLine("请输入网址!");
string url = Console.ReadLine();
Console.WriteLine("请输入储存图片的文件夹的路径.路径格式见txt文本");
string path = Console.ReadLine();
HttpCrawelHelper.CreatFile(path);
Console.WriteLine("请输入要储存的图片名称,要求是整数格式");
int name = int.Parse(Console.ReadLine());
HttpCrawelHelper.HttpGetHandle(url, path, name);
Console.ReadKey();
}
因为图片命名比较繁琐,毕竟世界上只有两种人,UserName和username,所以我直接用整数命名的。
接下来给大家看一下效果图。
最后认识一下吧,我叫闲齁齁,一枚用发量写代码的程序员,期待与大家一起成长一起进步。