C#中抓取网页方法小结 Ways to crawl web pages (get HTML) using C#

   注:原文亦在我MSN Blog上发表
   获取网页的HTML,大致有三种方法:1. 通过WebClient下载网页;2. 通过HttpWebRequest和HttpWebResponse获得网页的HTML;3. 通过微软提供的WebBrowser控件获得网页的Document Tree。解析HTML,主要方法有两种:正则表达式和Document Tree。以下分别给予简要介绍。

    本文只给出大致的实现思路,代码也较为简洁,只对各个思路给出简单的解释说明。

    预备知识:要获得网页的HTML,首先需要对HTTP协议中的Get和Post方法有简单的了解。Get方法是通过Uri向服务器提交请求,服务器根据Uri中指定的参数对客户端请求进行响应,返回请求的数据;而Post请求一般需要将提交的数据放到请求报文的body部分,还需要在报文首部Content-Length字段中指出body的长度,服务器收到Post请求后,在对这些请求数据进行处理后,再返回相应的响应数据。

    方法1:

    WebClient wClient = new WebClient();
    byte[] pageData = wClient.DownloadData("http://hjzlws.spaces.live.com/");
    string html = Encoding.UTF8.GetString(pageData);

    方法2:

    HttpWebRequest request = HttpWebRequest.Create("http://hjzlws.spaces.live.com/") as HttpWebRequest;
    request.Method = "GET";    
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
    string html = reader.ReadToEnd();
    reader.Close();

    关于此方法更详细的介绍,请参见如何使用 Visual C# 生成 GET 请求

    方法3:

    WebBrowser.Navigate("http://hjzlws.spaces.live.com/", .....);

    然后在WebBrowser的NavigateComplete事件中,得到Document Tree,就可以对网页的HTML进行处理了。关于此方法更详细的介绍,可以参见这篇文章

    对于Post方法,只需要在调用获得响应的方法前写入需要post的数据即可:

   1: string url = "http://www.ups.com/WebTracking/track";
   2: string postData = "loc=zh_cn&HTMLVersion=5.0&saveNumbers=null&trackNums
   3: =1ZX580116610381498&AgreeToTermsAndConditions=yes&track.x=17&track.y=4";
   4: string html = "";
   5: Encoding encode = Encoding.GetEncoding("GB2312");
   6: byte[] data = encode.GetBytes(postData);
   7: HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
   8: req.AllowAutoRedirect = true;
   9: req.Method = "POST";
  10: req.ContentType = "application/x-www-form-urlencoded";
  11: req.ContentLength = data.Length;  // 要Post的数据的长度
  12:  
  13: // 把要Post的Data写入(追加)到outStream对象中,使其具有post data
  14: Stream outStream = req.GetRequestStream();
  15: outStream.Write(data, 0, data.Length); 
  16: outStream.Close();
  17:  
  18: // Send Request and get the response
  19: HttpWebResponse response = req.GetResponse() as HttpWebResponse;
  20:  
  21: // 得到response的流
  22: Stream responseStream = response.GetResponseStream();
  23: StreamReader sr = new StreamReader(responseStream, encode);
  24:  
  25: html = sr.ReadToEnd();
  26: sr.Close();
    此外,如果需要在多个请求间维持同一个Session,只需要为各个请求的HttpWebRequest指定同一个CookieContainer即可。

你可能感兴趣的:(html)