抓取Web网页数据分析

Posted on 2007-02-20 11:24  dly  阅读(397)  评论(1)    收藏  举报

通过程序自动的读取其它网站网页显示的信息,类似于爬虫程序。比方说我们有一个系统,要提取BaiDu网站上歌曲搜索排名。分析系统在根据得到的数据进行数据分析。为业务提供参考数据。为了完成以上的需求,我们就需要模拟浏览器浏览网页,得到页面的数据在进行分析,最后把分析的结构,即整理好的数据写入数据库。那么我们的思路就是:
   1、发送HttpRequest请求。
   2、接收HttpResponse返回的结果。得到特定页面的html源文件。
   3、取出包含数据的那一部分源码。
   4、根据html源码生成HtmlDocument,循环取出数据。
   5、写入数据库。

程序如下:  

//根据Url地址得到网页的html源码
private string GetWebContent(string Url)
{
string strResult="";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
     //声明一个HttpWebRequest请求
request.Timeout = 30000;
//设置连接超时时间
request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.GetEncoding("GB2312");
StreamReader streamReader = new StreamReader(streamReceive, encoding);
strResult = streamReader.ReadToEnd();
}
catch
{
MessageBox.Show("出错");
}
return strResult;
}
为了使用HttpWebRequest和HttpWebResponse,需填名字空间引用
   using System.Net;

以下是程序具体实现过程:
private void button1_Click(object sender, EventArgs e)
{
//要抓取的URL地址
string Url = "http://list.mp3.baidu.com/topso/mp3topsong.html?id=1#top2";

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3