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();
}
}
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);//执行插入到数据库的操作
}
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有