在网上有很多关于C# WinForm获取网页内容的方法,但是查阅起来感觉总是杂乱无章的,完整的代码段也比较少,正好这一段时间在网上经常看到有小伙伴们询问C#获取网页HTML内容的问题,亦是美网络小编就抽空总结了几个常用的方法,下面就抛砖引玉的给大家说一下,希望对正在学习C#编程的小伙伴们能有所帮助。
以下C#代码均由亦是美网络小编在VS2017中编译执行,完美通过。
方法一:C# WinForm使用HttpWebRequest和HttpWebResponse获取网页内容
string url = @"http://www.baidu.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream,Encoding.Default);
string HtmlContent = sr.ReadToEnd();
richTextBox1.Text = HtmlContent;
response.Close();
stream.Close();
sr.Close();
方法二:C# WinForm使用WebRequest和WebResponse获取网页内容
string url = @"http://www.baidu.com";
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream,Encoding.Default);
string HtmlContent = sr.ReadToEnd();
richTextBox1.Text = HtmlContent;
response.Close();
stream.Close();
sr.Close();
方法三:C# WinForm使用WebClient获取网页内容
string url = @"http://www.baidu.com";
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(url);
StreamReader sr = new StreamReader(stream,Encoding.Default);
string HtmlContent = sr.ReadToEnd();
richTextBox1.Text = HtmlContent;
stream.Close();
sr.Close();
方法四:C# WinForm使用WebClient、DownloadString获取网页内容
string url = @"http://www.baidu.com";
WebClient wc = new WebClient();
string HtmlContent = wc.DownloadString(url);
richTextBox1.Text = HtmlContent;
方法五:C# WinForm使用WebBrowser获取网页内容
string url = @"http://www.baidu.com";
WebBrowser wb = new WebBrowser();
wb.ScriptErrorsSuppressed = true;//屏蔽JS错误弹出
wb.Navigate(url);
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(Wb_DocumentCompleted);
private void Wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = (WebBrowser)sender;
string HtmlContent = wb.DocumentText;
richTextBox1.Text = HtmlContent;
}
需要注意的是,每个网站的编码不尽相同,有的是UTF-8,有的是GB2312,在实际获取的过程中请根据自己的需要进行编码的设定。