using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string url = "https://example.com"; // 要爬取的网页URL
string htmlContent = await FetchHtmlAsync(url);
Console.WriteLine(htmlContent);
}
static async Task<string> FetchHtmlAsync(string url)
{
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
return string.Empty;
}
}
}
}
System.Net.Http 命名空间中的类来进行 HTTP 请求。Main 方法是程序的入口,使用 async Task 以支持异步操作。FetchHtmlAsync 方法用于发送 HTTP 请求并获取网页的 HTML 内容。HttpClient 发送 GET 请求,并确保请求成功。如果请求失败,则捕获异常并输出错误信息。这个简单的 C# 爬虫示例展示了如何使用 HttpClient 类来获取网页的 HTML 内容。实际应用中,你可能还需要解析 HTML 或处理更复杂的逻辑。
上一篇:c#生成随机数
下一篇:c#生成二维码
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站