如何使用C#检索网页?

bel*_*laz 20 c# http

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

Meh*_*ari 49

使用该System.Net.WebClient课程.

System.Console.WriteLine(new System.Net.WebClient().DownloadString(url));
Run Code Online (Sandbox Code Playgroud)

  • 性感的一个班轮......卖了!+1 (3认同)
  • 尼斯!:-) +1来自我!开门见山! (2认同)
  • 不过,这将是同步的.这意味着它只会在整个页面加载后显示数据. (2认同)

REA*_*REW 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();
Run Code Online (Sandbox Code Playgroud)

这是另一个选项,这次使用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));
}
Run Code Online (Sandbox Code Playgroud)

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


Ahm*_*med 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");
Run Code Online (Sandbox Code Playgroud)