2009-12-24 66 views
4

如何下载使用C#网页的网页?如何下载使用C#

+0

当你说“下载”,你的意思是你想要显示的页面,将其HTML保存到一个文件,或什么? – DOK 2009-12-24 20:22:51

回答

13

你可以使用WebClient

using (var client = new WebClient()) 
{ 
    string content = client.DownloadString("http://www.google.com"); 
} 
6

Darin的回答了这个,但另一种方法只需打开流:

FileStream s = new FileStream("http://www.someplace.com/somepage.html"); 

...然后阅读,就好像它是一个正常的文件。

4

如果你做的URL一些沉重的REST风格的节目,你可能要考虑可与REST Starter Kit Preview 2 HttpClient的。有了这个,你可以做这样的事情:

using (var client = new HttpClient()) 
{ 
    var page = client.Get("http://example.com").EnsureStatusIsSuccessful() 
        .Content.ReadAsString(); 
} 
0

下载会是什么达林季米特洛夫描述的最简单方法。

如果你想把所有的资源网页,例如图像,CSS。
你必须解析HTML代码DOM您下载后。
要做到这一点的最佳方式似乎是Html Agility Pack

1

使用WebClient类,然后设置请求标头,如果站点块页面的蜘蛛。

using System; 
using System.Net; 
using System.IO; 

public class Test 
{ 
    public static void Main (string[] args) 
    { 
     if (args == null || args.Length == 0) 
     { 
      throw new ApplicationException ("Specify the URI of the resource to retrieve."); 
     } 
     WebClient client = new WebClient(); 

     // Add a user agent header in case the 
     // requested URI contains a query. 

     client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 

     Stream data = client.OpenRead (args[0]); 
     StreamReader reader = new StreamReader (data); 
     string s = reader.ReadToEnd(); 
     Console.WriteLine (s); 
     data.Close(); 
     reader.Close(); 
    } 
}