当前位置: 移动技术网 > IT编程>开发语言>c# > 一个简单的C#爬虫程序

一个简单的C#爬虫程序

2019年11月23日  | 移动技术网IT编程  | 我要评论

    这篇这篇文章主要是展示了一个c#语言如何抓取网站中的图片。实现原理就是基于http请求。c#给我们提供了httpwebrequest和webclient两个对象,方便发送请求获取数据,下面看如何实

 


1,httpgetaction方法。用于发送请求获取数据后处理字符串得到图片地址

 1 public static void httpgetaction(string url,string path,int name)
 2         {
 3             stopwatch sw = new stopwatch();
 4             sw.start();
 5             console.writeline("抓取地址:" + url);
 6             string result = string.empty;
 7             httpwebrequest webrequest = webrequest.createhttp(url);
 8             webrequest.method = "get";
 9             var response= webrequest.getresponse();
10             using (streamreader reader = new streamreader((response as httpwebresponse).getresponsestream(), encoding.utf8))
11             {
12                 result = reader.readtoend();
13                 reader.close();
14             }
15             if (string.isnullorempty(result))
16             {
17                 console.writeline("请求地址错误");
18                 console.readkey();
19                 return;
20             }
21             //提取img标签src地址
22             regex regimg = new regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgurl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", regexoptions.ignorecase);
23             // 搜索匹配的字符串   
24             matchcollection matches = regimg.matches(result);
25             //爬取数量
26             int i = 0;
27             webclient web = new webclient();
28             // 取得匹配项列表   
29             foreach (match match in matches)
30             {
31                 string imgsrc = match.groups["imgurl"].value;
32                 if (imgsrc.contains("http") && !imgsrc.contains(".svg"))
33                 {
34                     i++;
35                     httpgetimg(web,imgsrc, path,name);
36                     name++;//图片名
37                 }
38             }
39             sw.stop();
40             console.writeline("爬取完成!总共爬取了" + i + "张图片!");
41             console.writeline("爬取图片耗时:" + sw.elapsedmilliseconds / 1000 + "秒");
42         }

 

2,httpgetimg方法。下载图片到指定目录

 1 public static void httpgetimg(webclient web, string src,string path,int name)
 2         {
 3             console.writeline("爬取图片:" + src);
 4             if (!directory.exists(path))
 5             {
 6                 console.writeline("路径错误!");
 7                 console.readkey();
 8                 return;
 9             }
10             web.downloadfile(src, path+name+".jpg");
11             console.writeline("爬取图片成功:" + name+".jpg");
12         }

 

3,控制台调用

1 static void main(string[] args)
2         {
3             string url= "https://www.xxxxxx.com/";
4             string path = path.combine(@"d:\word 资料\img\冬天\");
5             httphelper.httpgetaction(url,path,1);
6             console.readkey();
7         }

 

效果图:

 

 

一个简单的c#爬虫程序就完成了。如有错误的地方还望大神指点

 

原文来自:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网