.net获取网页的html代码

代码

namespace test
{
    
public partial class test : System.Web.UI.Page
    {
        
protected void Page_Load(object sender, EventArgs e)
        {
            
string sourceCode = GetSourceCode("http://www.baidu.com");
            Response.Write(sourceCode);
            Response.End();
            
        }
        
private string GetSourceCode(string url)
        {
            WebRequest req 
= WebRequest.Create(url);  //获取网页源代码
            string html = new StreamReader(req.GetResponse().GetResponseStream(), Encoding.GetEncoding("gb2312")).ReadToEnd();  //需指定网页的编码方式,如gb2312或 utf-8
            return html;
        }
    }
}

要加上:

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

命名空间。

原文地址:https://www.cnblogs.com/jxcia_Lai/p/1766643.html