C#中抓取網頁的方法

C#中抓取網頁的方法

獲取網頁的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("
    string html = Encoding.UTF8.GetString(pageData);

    方法2:

    HttpWebRequest request = HttpWebRequest.Create(" 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();

    關於此方法更詳細的介紹,請參見

    方法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即可。

http://it.chinawin.net/softwaredev/article-1e45.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章