Подтвердить что ты не робот

Как получить веб-страницу с помощью С#?

Как получить веб-страницу и diplay html на консоль с помощью С#?

4b9b3361

Ответ 1

Используйте класс System.Net.WebClient.

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

Ответ 2

Я придумал пример:

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

Второй вариант удобен, так как он не будет блокировать поток пользовательского интерфейса, что дает лучший опыт.

Ответ 3

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