using System; using System.Collections.Generic; using System.Text; using System.Timers; using System.Net; using System.Diagnostics; using System.IO; namespace ConsoleApplication1 { //<summary> //每隔5秒钟将指定网页的内容抓取下来,并以文件形式保存到c:/test目录中 //</summary> class GetWebPageInfo { public static string outFileName = ""; //生成的文件名 public static string myUrl = "http://bxg.cfchina.cn"; //要抓取的网页 public GetWebPageInfo() { //Timer mytimer = new Timer(); //mytimer.Elapsed += new ElapsedEventHandler(GetUrl);//指定定时器的事件 //mytimer.Interval = 5000;//每隔5秒抓一次 //mytimer.Start(); //mytimer.Enabled = true; //while (Console.Read() != 'q') //直到按小写字母q退出,否则一直抓取下去 //{ //} GetUrl(); } //定时器事件内容 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,则使用这句 Debug.WriteLine(pageHtml); outFileName = "C://test//" + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("-", "") + ".html"; using (StreamWriter sw = new StreamWriter(outFileName))//将获取的内容写入文本 { sw.Write(pageHtml); } Debug.WriteLine(outFileName); //输出保存后的文件名 } catch (WebException webEx) { Debug.WriteLine(webEx.Message.ToString()); } } } }