使用WebBrowser获取网页源代码,解决中文乱码问题

方法一:适合中文编码格式

System.IO.StreamReader getReader = new System.IO.StreamReader(this.webBrowser.DocumentStream, System.Text.Encoding.GetEncoding("gb2312"));

string gethtml = getReader.ReadToEnd();

 

方法二:自动获取网页编码格式

private void button1_Click(object sender, EventArgs e)

 {

      WebBrowser webBrowser = new WebBrowser();

      webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);

      webBrowser.Navigate(http://www.baidu.com/);

}

private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

{

      WebBrowser webBrowser = (WebBrowser)sender;

      if (webBrowser.ReadyState == WebBrowserReadyState.Complete)

      {

         //获取文档编码

          Encoding encoding = Encoding.GetEncoding(webBrowser.Document.Encoding);

          StreamReader stream = new StreamReader(webBrowser.DocumentStream, encoding);

          string htmlMessage = stream.ReadToEnd();   

      }

}

你可能感兴趣的:(object,String,Stream,button,encoding,WebBrowser)