ASP.NET網頁抓取數據


我的數據通過一個TextBox輸入,這些代碼是寫在一個button的點擊事件里的。

網頁數據抓取大概分為兩步,第一步是獲取網頁源代碼:

具體注釋如下:

         var currentUrl = TextBox1.Text;//獲得要抓取的網頁的URL地址
 
        var request = WebRequest.Create(currentUrl) as HttpWebRequest;//請求對象
        var response=request.GetResponse()as HttpWebResponse;//定義頁面回應對象
       

        var encode = string.Empty;
       
        encode = response.CharacterSet;//獲得網頁的編碼

 
        Stream stream;//數據流
        if (response.ContentEncoding.ToLower() == "gzip")
        {
            stream = new GZipStream(response.GetResponseStream(),    CompressionMode.Decompress);
        }
        else {
            stream = response.GetResponseStream();
        }//解壓縮
        var sr = new StreamReader(stream,Encoding.GetEncoding(encode));//定義數據流讀取對象
        var html = sr.ReadToEnd();
        sr.Close();
        HtmlDocument document=new HtmlDocument();
        document.LoadHtml(html);//將數據存入document

得到了網頁源代碼,接下來就是對其解析,就是第二步:

解析可以使用正則表達式或是Spilt等字符串操作方法。

根據源代碼寫出的Xpath,利用節點得到位於兩個節點之間的數據:

我的對象網頁就是我的博客主頁http://home.cnblogs.com/u/xuwanghu/

string sumLine = document.DocumentNode.SelectSingleNode("//body//ul[@id='user_profile']").InnerText;

string yuanlin = sumLine2.ToString().Split(':')[0].Split('博')[0];

這樣子,就將園齡存入了yuanlin,也就實現了抓取網頁數據的功能。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM