LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

.NET快速实现网页数据抓取

freeflydom
2024年5月25日 11:18 本文热度 357

前言

今天我们来讲讲如何使用.NET开源(MIT License)的轻量、灵活、高性能、跨平台的分布式网络爬虫框架DotnetSpider来快速实现网页数据抓取功能。

注意:为了自身安全请在国家法律允许范围内开发网页爬虫功能。

网页数据抓取需求

本文我们以抓取博客园10天推荐排行榜第一页的文章标题、文章简介和文章地址为示例,并把抓取下来的数据保存到对应的txt文本中。

请求地址:https://www.cnblogs.com/aggsite/topdiggs

创建控制台应用

创建名为DotnetSpiderExercise的控制台应用。



安装DotnetSpider NuGet包

NuGet包管理器搜索:DotnetSpider

 

添加Serilog日志组件

NuGet包管理器搜索:Serilog.AspNetCore

 


添加RecommendedRankingModel

namespace DotnetSpiderExercise

{

    public class RecommendedRankingModel

    {

        /// <summary>

        /// 文章标题

        /// </summary>

        public string ArticleTitle { get; set; }


        /// <summary>

        /// 文章简介

        /// </summary>

        public string ArticleSummary { get; set; }


        /// <summary>

        /// 文章地址

        /// </summary>

        public string ArticleUrl { get; set; }

    }

}

添加RecommendedRankingSpider

网页数据抓取的业务逻辑都在这里面。

using DotnetSpider.DataFlow.Parser;

using DotnetSpider.DataFlow;

using DotnetSpider.Downloader;

using DotnetSpider.Http;

using DotnetSpider.Scheduler.Component;

using DotnetSpider.Selector;

using DotnetSpider;

using Microsoft.Extensions.Logging;

using Microsoft.Extensions.Options;

using Serilog;

using DotnetSpider.Scheduler;

using Microsoft.Extensions.Hosting;

using System.Reflection;


namespace DotnetSpiderExercise

{

    public class RecommendedRankingSpider : Spider

    {

        public RecommendedRankingSpider(IOptions<SpiderOptions> options,

            DependenceServices services,

            ILogger<Spider> logger) : base(options, services, logger)

        {

        }


        public static async Task RunAsync()

        {

            var builder = Builder.CreateDefaultBuilder<RecommendedRankingSpider>();

            builder.UseSerilog();

            builder.UseDownloader<HttpClientDownloader>();

            builder.UseQueueDistinctBfsScheduler<HashSetDuplicateRemover>();

            await builder.Build().RunAsync();

        }


        protected override async Task InitializeAsync(CancellationToken stoppingToken = default)

        {

            //添加自定义解析

            AddDataFlow(new Parser());

            //使用控制台存储器

            AddDataFlow(new ConsoleStorage());

            //添加采集请求:博客园10天推荐排行榜

            await AddRequestsAsync(new Request("https://www.cnblogs.com/aggsite/topdiggs")

            {

                //请求超时10秒

                Timeout = 10000

            });

        }


        class Parser : DataParser

        {

            public override Task InitializeAsync()

            {

                return Task.CompletedTask;

            }


            protected override Task ParseAsync(DataFlowContext context)

            {

                var recommendedRankingList = new List<RecommendedRankingModel>();

                // 网页数据解析

                var number = 1;

                var recommendedList = context.Selectable.SelectList(Selectors.XPath(".//article[@class='post-item']"));

                foreach (var news in recommendedList)

                {

                    var articleTitle = news.Select(Selectors.XPath(".//a[@class='post-item-title']"))?.Value;

                    var articleSummary = news.Select(Selectors.XPath(".//p[@class='post-item-summary']"))?.Value?.Replace("\n", "").Replace(" ", "");

                    var articleUrl = news.Select(Selectors.XPath(".//a[@class='post-item-title']/@href"))?.Value;


                    Console.WriteLine($"第{number}篇文章 标题:{articleTitle}");


                    recommendedRankingList.Add(new RecommendedRankingModel

                    {

                        ArticleTitle = articleTitle,

                        ArticleSummary = articleSummary,

                        ArticleUrl = articleUrl

                    });


                    number++;

                }


                using (StreamWriter sw = new StreamWriter("RecommendedRanking.txt"))

                {

                    foreach (RecommendedRankingModel model in recommendedRankingList)

                    {

                        string line = $"文章标题:{model.ArticleTitle}\r\n文章简介:{model.ArticleSummary}\r\n文章地址:{model.ArticleUrl}";

                        sw.WriteLine(line + "\r\n ========================================================================================== \r\n");

                    }

                }

                return Task.CompletedTask;

            }

        }

    }

}


Program执行数据抓取

namespace DotnetSpiderExercise

{

    public class Program

    {

        static async Task Main(string[] args)

        {

            Console.WriteLine("网页数据抓取开始...");


            await RecommendedRankingSpider.RunAsync();


            Console.WriteLine("网页数据抓取完成...");

        }

    }

}

 

抓取数据和页面数据对比

抓取数据

 

页面数据

 




项目源码地址

GitHub源码地址:https://github.com/dotnetcore/DotnetSpider

GitHub wiki:https://github.com/dotnetcore/DotnetSpider/wiki

本文示例源码:https://github.com/YSGStudyHards/DotNetExercises/tree/master/DotnetSpiderExercise


转自:https://www.cnblogs.com/Can-daydayup/p/18208192 作者:追逐时光者


该文章在 2024/5/25 11:18:13 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved