这篇文章主要介绍了C#获取网页源代码的方法,涉及C#基于自定义函数读取网页html代码的方法,具有一定参考借鉴价值,需要的朋友可以参考下
本文实例讲述了C#获取网页源代码的方法。分享给大家供大家参考。具体如下:
- public string GetPageHTML(string url)
- {
- try
- {
- HttpWebRequest wr = WebRequest.Create(url) as HttpWebRequest;
- wr.Method = "get";
- wr.Accept = "*/*";
- wr.Headers.Add("Accept-Language: zh-cn");
- wr.Headers.Add("UA-CPU: x86");
- wr.Headers.Add("Accept-Encoding: gzip, deflate");
- wr.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Embedded Web Browser from: http://bsalsa.com/; InfoPath.2; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
- wr.KeepAlive = true;
- wr.ServicePoint.Expect100Continue = false;
- wr.AllowAutoRedirect = false;
- HttpWebResponse wre = wr.GetResponse() as HttpWebResponse;
- StreamReader sreader = new StreamReader(wre.GetResponseStream(), Encoding.GetEncoding("GBK"));
- string sHtml = sreader.ReadToEnd();
- wre.Close();
- return sHtml;
- }
- catch
- {
- return "";
- }
- }
希望本文所述对大家的C#程序设计有所帮助。
新闻热点
疑难解答