如何使用C#检索网页?

时间:2009-02-28 14:32:44

标签: c# http

如何检索网页并使用C#将html显示到控制台?

3 个答案:

答案 0 :(得分:49)

使用System.Net.WebClient类。

System.Console.WriteLine(new System.Net.WebClient().DownloadString(url));

答案 1 :(得分:19)

我敲了一个例子:

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线程,从而提供更好的体验。

答案 2 :(得分:5)

// 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");