刚刚完成一个简单的网络爬虫,因为在做的时候在网上像无头苍蝇一样找资料。发现了很多的资料,不过真正能达到我需要,有用的资料--代码很难找。所以我想发这篇文章让一些要做这个功能的朋友少走一些弯路。
首先是抓取Html源码,并选择<ul class="post_list"> </ul>节点的href:要添加 using System.IO;using System.Net;
01 | private void Search( string url) |
04 | WebRequest Request = WebRequest.Create(url.Trim()); |
06 | WebResponse Response = Request.GetResponse(); |
08 | Stream resStream = Response.GetResponseStream(); |
10 | StreamReader sr = new StreamReader(resStream, Encoding.Default); |
11 | StringBuilder sb = new StringBuilder(); |
12 | while ((rl = sr.ReadLine()) != null ) |
18 | string str = sb.ToString().ToLower(); |
20 | string str_get = mid(str, "<ul class=\"post_list\">" , "</ul>" ); |
28 | string strResult = mid(str_get, "href=\"" , "\"" , out start); |
29 | if (strResult == null ) |
33 | lab[url] += strResult; |
34 | str_get = str_get.Substring(start); |
42 | private string mid( string istr, string startString, string endString) |
44 | int iBodyStart = istr.IndexOf(startString, 0); |
47 | iBodyStart += startString.Length; |
48 | int iBodyEnd = istr.IndexOf(endString, iBodyStart); |
51 | iBodyEnd += endString.Length; |
52 | string strResult = istr.Substring(iBodyStart, iBodyEnd - iBodyStart - 1); |
57 | private string mid( string istr, string startString, string endString, out int iBodyEnd) |
62 | int iBodyStart = istr.IndexOf(startString, 0); |
65 | iBodyStart += startString.Length; |
66 | iBodyEnd = istr.IndexOf(endString, iBodyStart); |
69 | iBodyEnd += endString.Length; |
70 | string strResult = istr.Substring(iBodyStart, iBodyEnd - iBodyStart - 1); |
好了,上面就是全部代码了,如果你想要运行出来的话,有些细节要自己修改下。