如何使用C#下载网页?
你可以使用WebClient:
using (var client = new WebClient())
{
string content = client.DownloadString("http://www.google.com");
}
FileStream s = new FileStream("http://www.someplace.com/somepage.html");
...然后像普通文件一样读取。
如果你正在进行一些与URL相关的重度RESTful编程,那么你可能需要查看使用REST Starter Kit Preview 2提供的HttpClient。通过这个,你可以像这样做:
using (var client = new HttpClient())
{
var page = client.Get("http://example.com").EnsureStatusIsSuccessful()
.Content.ReadAsString();
}
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 ();
}
}
下载的最简单方法是Darin Dimitrov所描述的方式。
如果您想要网页的所有资源,例如图片、CSS等。
您必须在下载后解析HTML代码DOM。
似乎最好的方法是使用Html Agility Pack。