在本文中,我们展示了如何在 C# 中抓取网页。 C# 教程是有关 C# 语言的综合教程。
本教程显示了如何使用HttpWebRequest,WebClient,HttpClient,Flurl.Http和RestSharp读取页面。
在本教程的示例中,我们从一个小型网页 webcode.me 中读取了一个网页。
C# 使用HttpClient读取网页
HttpClient提供了一个基类,用于从 URI 标识的资源发送 HTTP 请求和接收 HTTP 响应。
Program.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异步抓取网页。
var content = await client.GetStringAsync("http://webcode.me");
await运算符将awaitable作为参数; 检查是否已经完成等待; 如果等待已完成,则该方法继续运行。 GetStringAsync()将内容读取为字符串,作为异步操作。
$ 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
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获取网页。
string content = client.DownloadString(url);
DownloadString()方法检索指定的资源。 此方法在下载资源时阻塞。
在第二个示例中,我们为WebClient提供了一种非阻塞方法。
Program.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 代码。 这次操作是异步的。
client.DownloadStringCompleted += (sender, e) =>{Console.WriteLine(e.Result);};
DownloadStringCompleted事件在异步资源下载操作完成时发生。
client.DownloadStringAsync(new Uri(url));
DownloadStringAsync方法下载指定为String或Uri的资源。 该方法不会阻塞调用线程。
C# 使用HttpWebRequest读取网页
HttpWebRequest类提供对属性和方法的支持,这些属性和方法使用户可以使用 HTTP 直接与服务器进行交互。 此 API 现在已标记为过时。
Program.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);}}}
该示例读取站点的内容并将其打印到控制台中。
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
用WebRequest.Create()方法创建一个HttpWebRequest。 它以 URL 作为参数。
using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
从请求中,我们使用GetResponse()方法获得了HttpWebResponse。
using (Stream stream = response.GetResponseStream())using (StreamReader reader = new StreamReader(stream)){html = reader.ReadToEnd();}
我们将网页的内容读入字符串。
Console.WriteLine(html);
数据被打印到控制台。
C# 使用Flurl.Http读取网页
Flurl.Http 是用于 C# 语言的流畅,可移植,可测试的 HTTP 第三方客户端库。
$ dotnet add package Flurl.Http
我们安装Flurl.Http包。
DownloadPageFlurl.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);}}}
该示例读取一个小型网页并将其内容打印到终端。
string result = await "http://webcode.me".GetStringAsync();
await运算符应用于异步方法中的任务,以暂停该方法的执行,直到等待的任务完成为止。 该任务代表正在进行的工作。 使用GetStringAsync()扩展方法检索数据。
用RestSharp读取网页
RestSharp 是.NET 的简单 REST 和 HTTP API 客户端。 它是一个第三方库。
$ dotnet add package RestSharp
我们安装RestSharp包。
Program.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 库获取网页的内容。 该网页是异步下载的。
var client = new RestClient("http://www.something.com");
使用RestClient类创建一个其他客户端。
var request = new RestRequest("", Method.GET);
使用RestRequest创建 GET 请求。
client.ExecuteAsync(request, response => {Console.WriteLine(response.Content);});
该请求使用ExecuteAsync()方法异步执行。
在本文中,我们展示了如何使用 C# 读取网页。 您可能也对以下相关教程感兴趣: MySQL C# 教程, C# 中的日期和时间,用 C# 读取文本文件或 C# Winforms 教程。
