asp.net 初步入门使用正则抓取网页信息

今天闲着没事看了看使用正则的使用,之前只是用来做验证,第一次用来抓取网页,

抓去了博客园首页几个分页的推荐文章列表。。。。

代码很简单就不做解释了,肯定做得不严谨,主要是熟悉下几个正则类和用于抓取网页内容的方法。。。

using System;
using System.Web;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
public partial class test : Page
{
public int g=0;
public string dfdf = "";
void Page_Load(object sender, System.EventArgs e)
{
for (int i = 2; i <10; i++)
{
WebRequest rque = WebRequest.Create("http://www.cnblogs.com/p"+i.ToString());
WebResponse utxt = rque.GetResponse();
Stream str = utxt.GetResponseStream();
StreamReader sread = new StreamReader(str, System.Text.Encoding.UTF8);

string pram = @"<h3><a class=""titlelnk"" href=""(.*?)"" target=""_blank"">(.*?)</a>";
MatchCollection m = Regex.Matches(sread.ReadToEnd(), pram);
foreach (Match ms in m)
{
g += 1;
dfdf = dfdf + ms.Groups[1].Value.ToString() + ms.Groups[2].Value.ToString() + "<br/><br/><br/><br/><br/>";
}
}

Response.Write("总记录数:"+g.ToString()+"<br/>"+dfdf);
}
}





原文地址:https://www.cnblogs.com/sishahu/p/2325326.html