如何检索网页并使用C#将html显示到控制台?
使用该System.Net.WebClient
课程.
System.Console.WriteLine(new System.Net.WebClient().DownloadString(url));
我敲了一个例子:
WebRequest r = WebRequest.Create("http://www.msn.com"); WebResponse resp = r.GetResponse(); using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { Console.WriteLine(sr.ReadToEnd()); } Console.ReadKey();
这是另一个选项,这次使用WebClient并以异步方式执行:
static void Main(string[] args) { System.Net.WebClient c = new WebClient(); c.DownloadDataCompleted += new DownloadDataCompletedEventHandler(c_DownloadDataCompleted); c.DownloadDataAsync(new Uri("http://www.msn.com")); Console.ReadKey(); } static void c_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { Console.WriteLine(Encoding.ASCII.GetString(e.Result)); }
第二个选项很方便,因为它不会阻止UI线程,从而提供更好的体验.
// Save HTML code to a local file. WebClient client = new WebClient (); client.DownloadFile("http://yoursite.com/page.html", @"C:\htmlFile.html"); // Without saving it. string htmlCode = client.DownloadString("http://yoursite.com/page.html");