软件编程
位置:首页>> 软件编程>> C#编程>> 基于C#实现网络爬虫 C#抓取网页Html源码

基于C#实现网络爬虫 C#抓取网页Html源码

作者:小虾Joe  发布时间:2022-11-16 22:19:05 

标签:C#,网络爬虫,抓取网页

最近刚完成一个简单的网络爬虫,开始的时候很迷茫,不知道如何入手,后来发现了很多的资料,不过真正能达到我需要,有用的资料--代码很难找。所以我想发这篇文章让一些要做这个功能的朋友少走一些弯路。

首先是抓取Html源码,并选择<ul class="post_list">  </ul>节点的href:要添加using System.IO;using 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, "<ul class=\"post_list\">", "</ul>");

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;
}

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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com