使用C# Winform应用程序获取网页源文件的解决方法
在C# Winform 应用程序中,获取某网页的源文件,可以用以下方法:
首先引入名称空间
using System.IO;
using System.Net;
WebClient MyWebClient = new WebClient(); MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据 Byte[] pageData = MyWebClient.DownloadData("http://www.baidu.com"); //string pageHtml = Encoding.Default.GetString(pageData); FileStream file = new FileStream("C:\\test.html", FileMode.Create); file.Write(pageData, 0, pageData.Length);
附,c# 获取网页源码的代码举例。
C# 获取指定网页HTML原代码可使用:WebClient WebRequest HttpWebRequest 三种方式。
当然也可使用webBrowse,有兴趣的朋友,可以自己研究下。
1,WebClient方式
private string GetWebClient(string url) { string strHTML = ""; WebClient myWebClient = new WebClient(); Stream myStream = myWebClient.OpenRead(url); StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("utf-8")); strHTML = sr.ReadToEnd(); myStream.Close(); return strHTML; }
2,WebRequest方式
private string GetWebRequest(string url) { Uri uri = new Uri(url); WebRequest myReq = WebRequest.Create(uri); WebResponse result = myReq.GetResponse(); Stream receviceStream = result.GetResponseStream(); StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8")); string strHTML = readerOfStream.ReadToEnd(); readerOfStream.Close(); receviceStream.Close(); result.Close(); return strHTML; }
3,HttpWebRequest方式
private string GetHttpWebRequest(string url) { Uri uri = new Uri(url); HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri); myReq.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705"; myReq.Accept = "*/*"; myReq.KeepAlive = true; myReq.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5"); HttpWebResponse result = (HttpWebResponse)myReq.GetResponse(); Stream receviceStream = result.GetResponseStream(); StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8")); string strHTML = readerOfStream.ReadToEnd(); readerOfStream.Close(); receviceStream.Close(); result.Close(); return strHTML; }
注意:“utf-8”应与指定网页的编码对应。
总结
HttpWebRequest 方式最复杂,但确提供了更多的选择性。
有的网站检测客户端的UserAgent!如163.com,如果使用WebClient WebRequest方式获取,将获取到的是错误提示页面的内容。
HttpWebRequest没有这个问题。
测试环境:WIN2003 + VS2005 + C# + winForm
赞 (0)