public class BlogRegexController : Controller { public void ExecuteRegex() { string strBaseUrl = "http://www.cnblogs.com/p"; //定义博客园可以访问的列表数据的基地址 for (int i = ; i <= ; i++)//因为博客园首页列表最大只有页,所以我们这个循环就执行次 { string strUrl = strBaseUrl + i.ToString(); BlogRege blogRegex = new BlogRege(); //定义的具体的Regex类 抓取博客园地址 string result = blogRegex.SendUrl(strUrl); blogRegex.AnalysisHtml(result);Response.Write("获取成功"); } }// // GET: /BlogRegex/public ActionResult Index() { ExecuteRegex(); return View(); }}在controller中的ExecuteRegex()方法就是执行抓取博客园列表数据的功臣。
public class BlogRege { //负责把数据插入到数据库中 使用到的是sqlhelper类 public void Insert(string title, string content,string linkurl, int categoryID = ) { SqlHelper helper = new SqlHelper(); helper.Insert(title, content, categoryID,linkurl); } /// <summary> /// 通过Url地址获取具体网页内容 发起一个请求获得html内容 /// </summary> /// <param name="strUrl"></param> /// <returns></returns> public string SendUrl(string strUrl) { try { WebRequest webRequest = WebRequest.Create(strUrl); WebResponse webResponse = webRequest.GetResponse(); StreamReader reader = new StreamReader(webResponse.GetResponseStream()); string result = reader.ReadToEnd(); return result; } catch (Exception ex) { throw ex; } } /// <summary> /// 分析Html 解析出里面具体的数据 /// </summary> /// <param name="htmlContent"></param> public void AnalysisHtml(string htmlContent) {//这个就是我在regulator正则表达式工具中拼接获取到的正则表达式 还有一点请注意就是转义字符的问题 string strPattern = "<div\s*class="post_item">\s*.*\s*.*\s*.*\s*.*\s*.*\s*.*\s*.*\s*<div\s*class="post_item_body">\s*<h><a\s*class="titlelnk"\s*href="(?<href>.*)"\s*target="_blank">(?<title>.*)</a>.*\s*<p\s*class="post_item_summary">\s*(?<content>.*)\s*</p>"; Regex regex = new Regex(strPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant); if (regex.IsMatch(htmlContent)) { MatchCollection matchCollection = regex.Matches(htmlContent); foreach (Match match in matchCollection) { string title = match.Groups[].Value;//获取到的是列表数据的标题 string content = match.Groups[].Value;//获取到的是内容 string linkurl=match.Groups[].Value;//获取到的是链接到的地址Insert(title, content,linkurl);//执行插入到数据库的操作 } } } }4.通过上面的代码我们可以很轻松的从博客园中获取我们用来测试的数据,方便快捷,而且真实,比我们手动输入的速度要快很多。
博客园每页列表是20条,一共200页,所以一共是4000条。数据抓取正确。
我以前说过,只是会代码的程序员不一定是合格程序员,程序员应该尽可能的减少自己的工作量,因为我们都是高智商的人。所以我们应该积极的学习各种对我们的工作有帮助的框架或者是方法,比如IOC、Entity Framework或Nhibernate框架来减轻我们开发维护代码的负担,毕竟我们听到需求要更改的反映,一般都是愤怒,然后大骂,最后才是修改。有些框架能够帮助我们,给我们维护代码带来好心情,何乐而不为呢。
我最后说一句,因为我要开发一个简单的仿照博客园的网站(MVC3),所以会用到各种技术准备,我提前写出来把这些要用到的内容整理一下,为以后的开发加速。
下一次,我准备整理一下在MVC中使用文本编辑器KindEditor的方法,希望大家如果有好的意见或者资料可以提供一下,让我也增加一些见识。谢谢各位