温馨提示×

c#怎么实现爬虫程序

c#
小亿
116
2023-08-18 07:04:41
栏目: 编程语言

在C#中实现爬虫程序可以使用HttpClient类来发送HTTP请求,并使用HtmlAgilityPack库来解析HTML页面。

下面是一个简单的示例代码,可以使用HttpClient发送GET请求,并使用HtmlAgilityPack解析HTML页面:

using System;
using System.Net.Http;
using HtmlAgilityPack;
namespace WebCrawler
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
var httpClient = new HttpClient();
var html = await httpClient.GetStringAsync("https://example.com"); // 替换成你想爬取的网页地址
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
// 解析页面并提取数据
var titleNode = htmlDocument.DocumentNode.SelectSingleNode("//title");
var descriptionNode = htmlDocument.DocumentNode.SelectSingleNode("//meta[@name='description']");
var title = titleNode?.InnerText;
var description = descriptionNode?.GetAttributeValue("content", "");
Console.WriteLine("Title: " + title);
Console.WriteLine("Description: " + description);
}
}
}

上述代码使用HttpClient发送GET请求获取网页内容,然后使用HtmlAgilityPack解析HTML页面。你可以根据需要修改代码来实现更复杂的爬虫功能,例如提取链接、遍历多个页面等。

0