[C#]GetHtmlSource

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

关键代码:

/// <summary>/// 获取网页HTML源码/// </summary>/// <param name="url">链接 eg:http://www.baidu.com/ </param>/// <param name="charset">编码 eg:Encoding.UTF8</param>/// <returns>HTML源码</returns>publicstaticstringGetHtmlSource(stringurl, Encoding charset)

{string_html =string.Empty;try{

HttpWebRequest _request = (HttpWebRequest)WebRequest.Create(url);

HttpWebResponse _response = (HttpWebResponse)_request.GetResponse();using(Stream _stream = _response.GetResponseStream())

{using(StreamReader _reader =newStreamReader(_stream, charset))

{

_html = _reader.ReadToEnd();

}

}

}catch(WebException ex)

{using(StreamReader sr =newStreamReader(ex.Response.GetResponseStream()))

{

_html = sr.ReadToEnd();

}

}catch(Exception ex)

{

_html = ex.Message;

}return_html;

}

.csharpcode, .csharpcodePRe

{

font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/

}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp{ background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt

{

background-color: #f4f4f4;

width: 100%;

margin: 0em;

}

.csharpcode .lnum { color: #606060; }测试代码:

publicstaticvoidGetHtmlSourceTest()

{string_url ="http://www.baidu.com/";string_htmlSource = HttpWebRequestUtilsV2.GetHtmlSource(_url, Encoding.UTF8);

Console.WriteLine(_htmlSource);

}

测试效果:

希望有所帮助!

.csharpcode, .csharpcode pre

{

font-size: small;

color: black;

font-family: consolas, "Courier New", courier, monospace;

background-color: #ffffff;

/*white-space: pre;*/

}

.csharpcode pre { margin: 0em; }

.csharpcode .rem { color: #008000; }

.csharpcode .kwrd { color: #0000ff; }

.csharpcode .str { color: #006080; }

.csharpcode .op { color: #0000c0; }

.csharpcode .preproc { color: #cc6633; }

.csharpcode .asp { background-color: #ffff00; }

.csharpcode .html { color: #800000; }

.csharpcode .attr { color: #ff0000; }

.csharpcode .alt

{

background-color: #f4f4f4;

width: 100%;

margin: 0em;

}

.csharpcode .lnum { color: #606060; }

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航