c#抓取网页数据( 简单网络@2011-09-0710:26小虾Joe阅读(6))
优采云 发布时间: 2021-10-15 01:05c#抓取网页数据(
简单网络@2011-09-0710:26小虾Joe阅读(6))
C#抓取网页Html源码(网络爬虫)
简单的网络爬虫的实现方法
我刚刚完成了一个简单的网络爬虫,因为我在做的时候,像无头苍蝇一样在网上找资料。找了很多资料,但确实能满足我的需求,有用的资料——代码难找。所以想发这个文章,让一些想做这个功能的朋友少走一些弯路。
首先是抓取Html源码,选择节点的href:使用System.IO添加;使用 System.Net;
private void Search(string url)
{
string rl;
WebRequest Request = WebRequest.Create(url.Trim());
WebResponse Response = Request.GetResponse();
Stream resStream = Response.GetResponseStream();
StreamReader sr = new StreamReader(resStream, Encoding.Default);
StringBuilder sb = new StringBuilder();
while ((rl = sr.ReadLine()) != null)
{
sb.Append(rl);
}
string str = sb.ToString().ToLower();
string str_get = mid(str, "", "");
int start = 0;
while (true)
{
if (str_get == null)
break;
string strResult = mid(str_get, "href=\"", "\"", out start);
if (strResult == null)
break;
else
{
lab[url] += strResult;
str_get = str_get.Substring(start);
}
}
}
private string mid(string istr, string startString, string endString)
{
int iBodyStart = istr.IndexOf(startString, 0); //开始位置
if (iBodyStart == -1)
return null;
iBodyStart += startString.Length; //第一次字符位置起的长度
int iBodyEnd = istr.IndexOf(endString, iBodyStart); //第二次字符在第一次字符位置起的首次位置
if (iBodyEnd == -1)
return null;
iBodyEnd += endString.Length; //第二次字符位置起的长度
string strResult = istr.Substring(iBodyStart, iBodyEnd - iBodyStart - 1);
return strResult;
}
private string mid(string istr, string startString, string endString, out int iBodyEnd)
{
//初始化out参数,否则不能return
iBodyEnd = 0;
int iBodyStart = istr.IndexOf(startString, 0); //开始位置
if (iBodyStart == -1)
return null;
iBodyStart += startString.Length; //第一次字符位置起的长度
iBodyEnd = istr.IndexOf(endString, iBodyStart); //第二次字符在第一次字符位置起的首次位置
if (iBodyEnd == -1)
return null;
iBodyEnd += endString.Length; //第二次字符位置起的长度
string strResult = istr.Substring(iBodyStart, iBodyEnd - iBodyStart - 1);
return strResult;
}
好了,以上就是全部代码了,要运行的话,有些细节还得自己修改。
发布于@2011-09-07 10:26 小虾乔阅读(12265)评论(6)编辑