欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# 實(shí)現(xiàn)抓取網(wǎng)站頁面內(nèi)容的實(shí)例方法

 更新時(shí)間:2013年08月19日 15:30:00   作者:  
這篇文章介紹了C# 實(shí)現(xiàn)抓取網(wǎng)站頁面內(nèi)容的實(shí)例方法,有需要的朋友可以參考一下

抓取新浪網(wǎng)的新聞欄目,如圖所示:

使用 谷歌瀏覽器的查看源代碼: 通過分析得知,我們所要找的內(nèi)容在以下兩個(gè)標(biāo)簽之間:

復(fù)制代碼 代碼如下:

<!-- publish_helper name='要聞-新聞' p_id='1' t_id='850' d_id='1' -->

內(nèi)容。。。。

<!-- publish_helper name='要聞-財(cái)經(jīng)' p_id='30' t_id='98' d_id='1' -->


如圖所示:

內(nèi)容。。。。

使用VS建立一個(gè)如圖所示的網(wǎng)站:

我們下載網(wǎng)絡(luò)數(shù)據(jù)主要通過   WebClient 類來實(shí)現(xiàn)。

使用下面源代碼獲取我們選擇的內(nèi)容:

復(fù)制代碼 代碼如下:

protected void Enter_Click(object sender, EventArgs e)
        {
            WebClient we = new WebClient();  //主要使用WebClient類
            byte[] myDataBuffer;
            myDataBuffer = we.DownloadData(txtURL.Text);  //該方法返回的是 字節(jié)數(shù)組,所以需要定義一個(gè)byte[]
            string download = Encoding.Default.GetString(myDataBuffer);  //對下載的數(shù)據(jù)進(jìn)行編碼

          
            //通過查詢源代碼,獲取某兩個(gè)值之間的新聞內(nèi)容
            int startIndex = download.IndexOf("<!-- publish_helper name='要聞-新聞' p_id='1' t_id='850' d_id='1' -->");
            int endIndex = download.IndexOf("<!-- publish_helper name='要聞-財(cái)經(jīng)' p_id='30' t_id='98' d_id='1' -->");

            string temp = download.Substring(startIndex, endIndex - startIndex + 1);  //截取新聞內(nèi)容

            lblMessage.Text = temp;//顯示所截取的新聞內(nèi)容
        }


效果如圖:

最后: 除了把下載的數(shù)據(jù)保存為文本以外,還可以保存為 文件類型 和 流 類型。

復(fù)制代碼 代碼如下:

WebClient wc = new WebClient();
            wc.DownloadFile(TextBox1.Text, @"F:\test.txt");
            Label1.Text = "文件下載完成";

復(fù)制代碼 代碼如下:

WebClient wc = new WebClient();
            Stream  s =  wc.OpenRead(TextBox1.Text);

            StreamReader sr = new StreamReader(s);
            Label1.Text =  sr.ReadToEnd();

相關(guān)文章

最新評論