代码改变世界

C# 抓取网页Html源码 (网络爬虫)

2011-09-07 18:09  TTlive  阅读(696)  评论(0编辑  收藏  举报

刚刚完成一个简单的网络爬虫,因为在做的时候在网上像无头苍蝇一样找资料。发现了很多的资料,不过真正能达到我需要,有用的资料--代码很难找。所以我想发这篇文章让一些要做这个功能的朋友少走一些弯路。

首先是抓取Html源码,并选择<ul class="post_list">  </ul>节点的href:要添加 using System.IO;using System.Net;

01 private void Search(string url)
02 {
03     string rl;
04     WebRequest Request = WebRequest.Create(url.Trim());
05  
06     WebResponse Response = Request.GetResponse();
07  
08     Stream resStream = Response.GetResponseStream();
09  
10     StreamReader sr = new StreamReader(resStream, Encoding.Default);
11     StringBuilder sb = new StringBuilder();
12     while ((rl = sr.ReadLine()) != null)
13     {
14         sb.Append(rl);
15     }
16  
17  
18     string str = sb.ToString().ToLower();
19  
20     string str_get = mid(str, "<ul class=\"post_list\">", "</ul>");
21  
22  
23     int start = 0;
24     while (true)
25     {
26         if (str_get == null)
27             break;
28         string strResult = mid(str_get, "href=\"", "\"", out start);
29         if (strResult == null)
30             break;
31         else
32         {
33             lab[url] += strResult;
34             str_get = str_get.Substring(start);
35         }
36     }
37 }
38  
39  
40  
41  
42 private string mid(string istr, string startString, string endString)
43 {
44     int iBodyStart = istr.IndexOf(startString, 0);               //开始位置
45     if (iBodyStart == -1)
46         return null;
47     iBodyStart += startString.Length;                           //第一次字符位置起的长度
48     int iBodyEnd = istr.IndexOf(endString, iBodyStart);         //第二次字符在第一次字符位置起的首次位置
49     if (iBodyEnd == -1)
50         return null;
51     iBodyEnd += endString.Length;                              //第二次字符位置起的长度
52     string strResult = istr.Substring(iBodyStart, iBodyEnd - iBodyStart - 1);
53     return strResult;
54 }
55  
56  
57 private string mid(string istr, string startString, string endString, out int iBodyEnd)
58 {
59     //初始化out参数,否则不能return
60     iBodyEnd = 0;
61  
62     int iBodyStart = istr.IndexOf(startString, 0);               //开始位置
63     if (iBodyStart == -1)
64         return null;
65     iBodyStart += startString.Length;                           //第一次字符位置起的长度
66     iBodyEnd = istr.IndexOf(endString, iBodyStart);         //第二次字符在第一次字符位置起的首次位置
67     if (iBodyEnd == -1)
68         return null;
69     iBodyEnd += endString.Length;                              //第二次字符位置起的长度
70     string strResult = istr.Substring(iBodyStart, iBodyEnd - iBodyStart - 1);
71     return strResult;
72 }

好了,上面就是全部代码了,如果你想要运行出来的话,有些细节要自己修改下。