C#獲得網頁HTML源碼實例。本站提示廣大學習愛好者:(C#獲得網頁HTML源碼實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#獲得網頁HTML源碼實例正文
本文實例講述了C#獲得網頁HTML源碼的辦法,分享給年夜家供年夜家參考。詳細辦法以下:
症結代碼以下:
/// <summary>
/// 獲得網頁HTML源碼
/// </summary>
/// <param name="url">鏈接 eg:http://www.百度.com/ </param>
/// <param name="charset">編碼 eg:Encoding.UTF8</param>
/// <returns>HTML源碼</returns>
public static string GetHtmlSource(string url, 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 = new StreamReader(_stream, charset))
{
_html = _reader.ReadToEnd();
}
}
}
catch (WebException ex)
{
using (StreamReader sr = new StreamReader(ex.Response.GetResponseStream()))
{
_html = sr.ReadToEnd();
}
}
catch (Exception ex)
{
_html = ex.Message;
}
return _html;
}
測試代碼以下:
public static void GetHtmlSourceTest()
{
string _url = "http://www.百度.com/";
string _htmlSource = HttpWebRequestUtilsV2.GetHtmlSource(_url, Encoding.UTF8);
Console.WriteLine(_htmlSource);
}
測試後果以下圖所示:
願望本文所述對年夜家的C#法式設計有所贊助