標籤:blog http 使用 os io 檔案 資料 art
轉載自 :http://blog.csdn.net/gisfarmer/article/details/2836904
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net;
- using System.IO;
- namespace thief
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- try {
- WebClient MyWebClient = new WebClient();
- MyWebClient.Credentials = CredentialCache.DefaultCredentials;//擷取或設定用於對向Internet資源的請求進行身分識別驗證的網路憑據。
- Byte[] pageData = MyWebClient.DownloadData(http://www.163.com); //從指定網站下載資料
- string pageHtml = Encoding.Default.GetString(pageData); //如果擷取網站頁面採用的是GB2312,則使用這句
- //string pageHtml = Encoding.UTF8.GetString(pageData); //如果擷取網站頁面採用的是UTF-8,則使用這句
- Console.WriteLine(pageHtml);//在控制台輸入擷取的內容
- using (StreamWriter sw = new StreamWriter("c://test//ouput.html"))//將擷取的內容寫入文本
- {
- sw.Write(pageHtml);
- }
- Console.ReadLine(); //讓控制台暫停,否則一閃而過了
- }
- catch(WebException webEx) {
- Console.WriteLine(webEx.Message.ToString());
- }
- }
- }
- }
改進一下,加入定時器後
- using System;
- using System.Text;
- using System.Timers;
- using System.Net;
- using System.IO;
- //<summary>
- //每隔5秒鐘將指定網頁的內容抓取下來,並以檔案形式儲存到c:/test目錄中
- //</summary>
- namespace TimerTest
- {
- class Program
- {
- public static string outFileName = ""; //產生的檔案名稱
- public static string myUrl = "http://bxg.cfchina.cn"; //要抓取的網頁
- static void Main(string[] args)
- {
- Timer mytimer = new Timer();
- mytimer.Elapsed +=new ElapsedEventHandler(GetUrl);//指定定時器的事件
- mytimer.Interval = 5000;//每隔5秒抓一次
- mytimer.Start();
- mytimer.Enabled = true;
- while (Console.Read() != ‘q‘) //直到按小寫字母q退出,否則一直抓取下去
- {
- }
- }
- //定時器事件內容
- static void GetUrl(object source, ElapsedEventArgs e)
- {
- try
- {
- WebClient MyWebClient = new WebClient();
- MyWebClient.Credentials = CredentialCache.DefaultCredentials;//擷取或設定用於對向Internet資源的請求進行身分識別驗證的網路憑據。
- Byte[] pageData = MyWebClient.DownloadData(myUrl);//從指定網站下載資料
- string pageHtml = Encoding.Default.GetString(pageData); //如果擷取網站頁面採用的是GB2312,則使用這句
- //string pageHtml = Encoding.UTF8.GetString(pageData); //如果擷取網站頁面採用的是UTF-8,則使用這句
- //Console.WriteLine(pageHtml);//在控制台輸入擷取的內容
- outFileName = "C://test//" + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("-", "") + ".html";
- using (StreamWriter sw = new StreamWriter(outFileName))//將擷取的內容寫入文本
- {
- sw.Write(pageHtml);
- }
- Console.WriteLine(outFileName); //輸出儲存後的檔案名稱
- }
- catch (WebException webEx)
- {
- Console.WriteLine(webEx.Message.ToString());
- }
- }
- }
- }