💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 在 C# 中读取网页 > 原文: [https://zetcode.com/csharp/readwebpage/](https://zetcode.com/csharp/readwebpage/) 在本文中,我们展示了如何在 C# 中抓取网页。 [C# 教程](http://zetcode.com/lang/csharp/)是有关 C# 语言的综合教程。 本教程显示了如何使用`HttpWebRequest`,`WebClient`,`HttpClient`,`Flurl.Http`和`RestSharp`读取页面。 在本教程的示例中,我们从一个小型网页 [webcode.me](http://www.webcode.me) 中读取了一个网页。 ## C# 使用`HttpClient`读取网页 `HttpClient`提供了一个基类,用于从 URI 标识的资源发送 HTTP 请求和接收 HTTP 响应。 `Program.cs` ```cs using System; using System.Net.Http; using System.Threading.Tasks; namespace DownloadPageHttpClient { class Program { static async Task Main(string[] args) { using var client = new HttpClient(); client.DefaultRequestHeaders.Add("User-Agent", "C# console program"); var content = await client.GetStringAsync("http://webcode.me"); Console.WriteLine(content); } } } ``` 该代码示例使用`HttpClient`异步抓取网页。 ```cs var content = await client.GetStringAsync("http://webcode.me"); ``` `await`运算符将`awaitable`作为参数; 检查是否已经完成等待; 如果等待已完成,则该方法继续运行。 `GetStringAsync()`将内容读取为字符串,作为异步操作。 ```cs $ dotnet run <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My html page</title> </head> <body> <p> Today is a beautiful day. We go swimming and fishing. </p> <p> Hello there. How are you? </p> </body> </html> ``` 这是输出。 ## 用`WebClient`读取网页 `WebClient`提供了用于向 URI 标识的资源发送数据和从中接收数据的通用方法。 `Program.cs` ```cs using System; using System.Net; namespace DownloadPageWebClient { class Program { static void Main(string[] args) { using var client = new WebClient(); client.Headers.Add("User-Agent", "C# console program"); string url = "http://webcode.me"; string content = client.DownloadString(url); Console.WriteLine(content); } } } ``` 该代码示例使用`WebClient`获取网页。 ```cs string content = client.DownloadString(url); ``` `DownloadString()`方法检索指定的资源。 此方法在下载资源时阻塞。 在第二个示例中,我们为`WebClient`提供了一种非阻塞方法。 `Program.cs` ```cs using System; using System.Net; using System.Threading.Tasks; namespace DownloadPageWebClientAsync { class Program { static void Main(string[] args) { using var client = new WebClient(); client.DownloadStringCompleted += (sender, e) => { Console.WriteLine(e.Result); }; string url = "http://www.webcode.me"; client.DownloadStringAsync(new Uri(url)); Console.ReadLine(); } } } ``` 该代码示例使用`WebClient`获取网页的 HTML 代码。 这次操作是异步的。 ```cs client.DownloadStringCompleted += (sender, e) => { Console.WriteLine(e.Result); }; ``` `DownloadStringCompleted`事件在异步资源下载操作完成时发生。 ```cs client.DownloadStringAsync(new Uri(url)); ``` `DownloadStringAsync`方法下载指定为`String`或`Uri`的资源。 该方法不会阻塞调用线程。 ## C# 使用`HttpWebRequest`读取网页 `HttpWebRequest`类提供对属性和方法的支持,这些属性和方法使用户可以使用 HTTP 直接与服务器进行交互。 此 API 现在已标记为过时。 `Program.cs` ```cs using System; using System.Net; using System.IO; namespace DownloadPageHttpWebRequest { class Program { static void Main(string[] args) { string html = string.Empty; string url = "http://webcode.me"; HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); request.UserAgent = "C# console client"; using (HttpWebResponse response = (HttpWebResponse) request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { html = reader.ReadToEnd(); } Console.WriteLine(html); } } } ``` 该示例读取站点的内容并将其打印到控制台中。 ```cs HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); ``` 用`WebRequest.Create()`方法创建一个`HttpWebRequest`。 它以 URL 作为参数。 ```cs using (HttpWebResponse response = (HttpWebResponse) request.GetResponse()) ``` 从请求中,我们使用`GetResponse()`方法获得了`HttpWebResponse`。 ```cs using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { html = reader.ReadToEnd(); } ``` 我们将网页的内容读入字符串。 ```cs Console.WriteLine(html); ``` 数据被打印到控制台。 ## C# 使用`Flurl.Http`读取网页 Flurl.Http 是用于 C# 语言的流畅,可移植,可测试的 HTTP 第三方客户端库。 ```cs $ dotnet add package Flurl.Http ``` 我们安装`Flurl.Http`包。 `DownloadPageFlurl.cs` ```cs using System; using System.Threading.Tasks; using Flurl.Http; namespace DownloadPageFlurl { class Program { static async Task Main(string[] args) { string result = await "http://webcode.me".GetStringAsync(); Console.WriteLine(result); } } } ``` 该示例读取一个小型网页并将其内容打印到终端。 ```cs string result = await "http://webcode.me".GetStringAsync(); ``` `await`运算符应用于异步方法中的任务,以暂停该方法的执行,直到等待的任务完成为止。 该任务代表正在进行的工作。 使用`GetStringAsync()`扩展方法检索数据。 ## 用`RestSharp`读取网页 RestSharp 是.NET 的简单 REST 和 HTTP API 客户端。 它是一个第三方库。 ```cs $ dotnet add package RestSharp ``` 我们安装`RestSharp`包。 `Program.cs` ```cs using System; using RestSharp; namespace DownloadPageRestSharp { class Program { static void Main(string[] args) { var client = new RestClient("http://webcode.me"); var request = new RestRequest("", Method.GET); client.ExecuteAsync(request, response => { Console.WriteLine(response.Content); }); Console.ReadLine(); } } } ``` 该代码示例使用 RestSharp 库获取网页的内容。 该网页是异步下载的。 ```cs var client = new RestClient("http://www.something.com"); ``` 使用`RestClient`类创建一个其他客户端。 ```cs var request = new RestRequest("", Method.GET); ``` 使用`RestRequest`创建 GET 请求。 ```cs client.ExecuteAsync(request, response => { Console.WriteLine(response.Content); }); ``` 该请求使用`ExecuteAsync()`方法异步执行。 在本文中,我们展示了如何使用 C# 读取网页。 您可能也对以下相关教程感兴趣: [MySQL C# 教程](/db/mysqlcsharptutorial/), [C# 中的日期和时间](/articles/csharpdatetime/),[用 C# 读取文本文件](/articles/csharpreadtext/)或 [C# Winforms 教程](/gui/csharpwinforms/)。