aspx頁面轉html

這是我整理的一個直接將指定頁面的源碼獲取到,然後保存成另外一個頁面的方法。

using System.IO;
using System.Text;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Response.Write(GetPage("http://www.baidu.com", Encoding.UTF8));
        //Response.Write(HttpContext.Current.Server.MapPath("a.html"));
        CreatPage(GetPage("http://www.baidu.com", Encoding.UTF8), "a.html", Encoding.UTF8);
        Response.Redirect("a.html");}
    }


    /// <summary>
    /// 創建Web頁面
    /// </summary>
    /// <param name="html">要生成的頁面HTML字符串</param>
    /// <param name="path">要生成的頁面的保存路徑</param>
    /// <param name="encoding">頁面編碼</param>
    public static void CreatPage(string html, string path, Encoding encoding)
    {
        StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(path), false, encoding);
        sw.WriteLine(html);
        sw.Flush();
        sw.Close();
    }


    /// <summary>
    /// 獲取指定頁面的HTML代碼
    /// </summary>
    /// <param name="url">要獲取的頁面的URL路徑</param>
    /// <param name="encoding">頁面編碼</param>
    /// <returns></returns>
    public static string GetPage(string url, Encoding encoding)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Timeout = 20000;
        request.AllowAutoRedirect = false;


        string html = string.Empty;
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
                html = reader.ReadToEnd();
                reader.Close();
            }
        }
        return html;
    }
}

發佈了2 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章