在 C# 中构建网络爬虫

在 C# 中构建网络爬虫:分步教程

在本文中,我将向您介绍如何在 C# 中构建网络爬虫。我们将一步一步从头开始。最后,您将拥有一个高效、可扩展的爬虫,随时收集所需的数据。

让我们开始吧!

什么是网络爬虫?

网络爬虫、蜘蛛或机器人是一种自动程序,可系统地浏览网页、发现链接并收集数据。与以特定数据提取为目标的网络刮擦不同,网络爬虫侧重于浏览网站并构建网站内容的结构图。爬虫还可以集成刮擦功能,在探索链接的同时提取相关数据。

比较网络抓取与网络爬取 这里.

构建网络爬虫的替代方案

如果您觉得构建和维护网络爬虫令人难以承受,Bright Data 可提供强大的替代方案来简化您的工作流程。使用 网络抓取 API 轻松提取或访问结构化数据 即用型数据集 根据您的需求量身定制。这些解决方案可以节省时间、轻松扩展,并包含验证码解决、IP 轮换和遵守隐私法等功能,让您专注于分析数据,而不是收集数据。

我与 Bright Data 没有任何关系,这只是一个建议。

在 C# 中构建网络爬虫的前提条件

开始之前,请确保您拥有以下工具和库:

  • .NET SDK(第 8 版或更高版本): 从官方 微软 .NET 网站.
  • IDE: 使用带有 C# 扩展的 Visual Studio 2022 或 Visual Studio Code。
  • NuGet 软件包管理器 包含在 Visual Studio 中,用于安装依赖项,如 Html 敏捷包 和 CsvHelper.

步骤 1:设置环境

首先创建一个新的控制台应用程序:

mkdir web-crawler
CD web-crawler
dotnet new console - framework net8.0

安装依赖项

使用 NuGet 添加以下库:

  • Html 敏捷包:用于解析 HTML。
dotnet add package HtmlAgilityPack
  • Html Agility Pack CSS 选择器:简化了使用 CSS 选择器选择元素的过程。
dotnet add package HtmlAgilityPack.CssSelectors
  • CsvHelper:用于将数据导出为 CSV 文件。
dotnet add package CsvHelper

步骤 2:编写基本爬虫程序

加载网页

设置程序,获取并解析网页:

using HtmlAgilityPack;

class Program
{
    static void Main(string[] args)
    {
        var web = new HtmlWeb();
        var document = web.Load("https://example.com");

        Console.WriteLine("Page loaded successfully!");
    }
}

运行应用程序:

dotnet run

发现链接

展开代码,识别页面上的链接。使用 HtmlAgilityPack 查找所有 <a> 元素,并提取其 href 属性:

var links = document.DocumentNode.SelectNodes("//a[@href]");
foreach (var link in links)
{
    var url = link.GetAttributeValue("href", string.Empty);
    Console.WriteLine($"Found URL: {url}");
}

步骤 3:管理抓取过程

要系统地抓取多个页面,应维护一个要访问的 URL 队列和一个已发现的 URL 列表,以避免重复。

实施 URL 队列

使用 排队 为要访问的 URL 和 哈希集合 来跟踪访问过的 URL:

var urlsToVisit = new Queue<string>();
var visitedUrls = new HashSet<string>();

urlsToVisit.Enqueue("https://example.com");

while (urlsToVisit.Count > 0)
{
    var currentUrl = urlsToVisit.Dequeue();
    if (visitedUrls.Contains(currentUrl)) continue;

    visitedUrls.Add(currentUrl);
    Console.WriteLine($"Crawling: {currentUrl}");

    var currentDocument = web.Load(currentUrl);
    var links = currentDocument.DocumentNode.SelectNodes("//a[@href]");
    if (links == null) continue;

    foreach (var link in links)
    {
        var url = link.GetAttributeValue("href", string.Empty);
        if (!visitedUrls.Contains(url))
        {
            urlsToVisit.Enqueue(url);
        }
    }
}

步骤 4:从页面提取数据

构建数据

定义 Product 类来存储搜索到的数据:

public class Product
{
    public string Name { get; set; }
    public string Price { get; set; }
    public string ImageUrl { get; set; }
}

刮削产品

更新爬网程序,以便在每个页面上查找和处理产品元素:

var products = new List();
foreach (var productNode in currentDocument.DocumentNode.SelectNodes("//li[@class='product']"))
{
    var name = productNode.SelectSingleNode(".//h2").InnerText.Trim();
    var price = productNode.SelectSingleNode(".//span[@class='price']").InnerText.Trim();
    var imageUrl = productNode.SelectSingleNode(".//img").GetAttributeValue("src", string.空);

    products.Add(new Product { Name = name, Price = price, ImageUrl = imageUrl });
    Console.WriteLine($"Found product: {name}");
}

第 5 步:将数据保存为 CSV 文件

使用 CsvHelper 将收集到的产品数据导出为 CSV 文件:

using CsvHelper;
using System.Globalization;
using System.IO;

using (var writer = new StreamWriter("products.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(products);
}

运行应用程序,生成 products.csv 文件,其中包含所有搜索到的数据。

步骤 6:优化爬网程序

  • 平行爬行:使用 任务运行.
  • 处理动态内容:使用 PuppeteerSharp 用于 JavaScript 渲染的页面。
  • 避免障碍:轮换用户代理,尊重 robots.txt并引入延迟。

结论

在 C# 中构建网络爬虫需要探索网页、提取所需数据并确保其顺利运行。有了本指南,您就可以应对任何网络数据项目了。祝您好运,爬行愉快!

类似文章