如何使用 C# 检索网页?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/598075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:45:08  来源:igfitidea点击:

How to retrieve a webpage with C#?

c#http

提问by belaz

How to retrieve a webpage and diplay the html to the console with C# ?

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

采纳答案by Mehrdad Afshari

Use the System.Net.WebClientclass.

使用System.Net.WebClient类。

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

回答by REA_ANDREW

I have knocked up an example:

我举了一个例子:

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();

Here is another option, using the WebClient this time and do it asynchronously:

这是另一种选择,这次使用 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));
}

The second option is handy as it will not block the UI Thread, giving a better experience.

第二个选项很方便,因为它不会阻塞 UI 线程,从而提供更好的体验。

回答by Ahmed Atia

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