溫馨提示×

c#怎么實現爬蟲程序

c#
小億
136
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女