为了提取一个网站的资料写了一个小偷程序:
比如:HTML源码中
title="编号:建标 7-1959 
标题:碳酸镁石棉粉
英文标题: 
....颁布日期:2000-12-1">
是需要提取出来的内容,当然如果需要提的更细,可以用正则表达式提取.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;//提取网页数据用到此类
public partial class _1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void btnReturn_Click(object sender, System.EventArgs e)
{
//测试地址:http://www.csres.com/searchResult.jsp
string url = txtUrl.Text.Trim(); //获取输入的网页地址
WebRequest wreq = WebRequest.Create(url);
HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
string HTML = "";
Stream s = wresp.GetResponseStream();
StreamReader objReader = new StreamReader(s, System.Text.Encoding.GetEncoding("GB2312"));
string sLine = "";
int i = 0;
while (sLine != null)
{
i++;
sLine = objReader.ReadLine();
if (sLine != null)
HTML += sLine;
}
String temp = "";
Regex re = new Regex(@"编号(.*?)/">", RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in re.Matches(HTML))
{
temp+=m.Groups[1].Value;
}
txtBody.Text = temp;
} 
}
WebClient 类提供三种从资源下载数据的方法:
DownloadData 从资源下载数据并返回字节数组。
DownloadFile 从资源将数据下载到本地文件。
OpenRead 从资源以 Stream 的形式返回数据。
这里是采用最后一种
本文介绍了一种使用C#实现的网页数据抓取方法,通过发送HTTP请求获取目标网页的内容,并利用正则表达式提取所需信息。具体展示了如何读取网页源码、匹配特定格式的数据等关键技术步骤。

150

被折叠的 条评论
为什么被折叠?



