博客园首页代码:线建立一个MVC空项目(图)

优采云 发布时间: 2021-06-29 19:13

  博客园首页代码:线建立一个MVC空项目(图)

  \\s*.*)\”\\s*target=\”_blank\”>(?.*).*\\s*

  \\s*(?.*)\\s*

  ”

  原理很简单。下面我将给出源码:创建一个空的MVC项目,在Controller文件下添加一个控制器HomeController,并为控制器添加一个视图索引

  HomeController.cs 代码的一部分:

  

  using System;

using System.Collections.Generic;

using System.IO;

using System.Net;

using System.Text.RegularExpressions;

using System.Web.Mvc;

namespace WebApplication1.Controllers

{

public class HomeController : Controller

{

///

/// 通过Url地址获取具体网页内容 发起一个请求获得html内容

///

///

///

public static 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;

}

}

public ActionResult Index()

{

string strPattern = "\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*.*\\s*\\s*(?.*)</a>.*\\s*\\s*(?.*)\\s*";

List list = new List();

Regex regex = new Regex(strPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant);

if (regex.IsMatch(SendUrl("http://www.cnblogs.com/")))

{

MatchCollection matchCollection = regex.Matches(SendUrl("http://www.cnblogs.com/"));

foreach (Match match in matchCollection)

{

List one_list = new List();

one_list.Add(match.Groups[2].Value);//获取到的是列表数据的标题

one_list.Add(match.Groups[3].Value);//获取到的是内容

one_list.Add(match.Groups[1].Value);//获取到的是链接到的地址

list.Add(one_list);

}

}

ViewBag.list = list;

return View();

}

}

}</p>

  

  部分索引视图代码:

  

  @{

Layout = null;

}

Index

#customers {

font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;

width: 100%;

border-collapse: collapse;

outline: #00ff00 dotted thick;

}

#customers td, #customers th {

font-size: 1em;

border: 1px solid #98bf21;

padding: 3px 7px 2px 7px;

}

#customers th {

font-size: 1.1em;

text-align: left;

padding-top: 5px;

padding-bottom: 4px;

background-color: #A7C942;

color: #ffffff;

}

标题

内容

链接

@foreach (var a in ViewBag.list)

{

int count = 0;

@foreach (string b in a)

{

if (++count == 3)

{

@HttpUtility.HtmlDecode(b)@*使转义符正常输出*@

}

else if(count==1)

{

@HttpUtility.HtmlDecode(b)

}

else

{

@HttpUtility.HtmlDecode(b)

}

}

}

  

  如博客所写,可以运行一个完整的MVC项目,但是我只采集一页,我们也可以在博客园首页采集下翻页部分(即pager_buttom)采集

  p>

  

  ,只需要添加实现分页的方法,这里就不贴代码了,自己试试吧。但是,如果要将信息导入到数据库中,则需要创建相应的表,然后根据表中的属性从html中一一采集提取所需的相应信息。另外,我们不应该将采集添加到每个新闻条目对应的页面的源代码中,而每个新闻条目对应的链接都应该存储在数据库中。原因是下载大量新闻页面需要花费大量时间。佩服采集的效率,在数据库中存放大量新闻页面文件会占用大量内存,影响数据库性能。

  转载于:

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线