欢迎光临散文网 会员登陆 & 注册

用AngleSharp & LINQPad抓取分析博客园排行榜

2023-02-09 12:01 作者:百宝门  | 我要投稿

AngleSharp简单介绍

  1. AngleSharp 是一个 .NET库

  2. 使您能够解析基于尖括号的超文本,如 HTML、SVG、MathML、XML

  3. AngleSharp的一个重要方面是 CSS也可以解析

  4. 同时还是开源,免费的

Github: https://github.com/AngleSharp/AngleSharp使用文档: https://anglesharp.github.io/

开发工具的推荐 LINQPad

介绍:一个小巧,打开秒速,随时能写C#,不至于灵感快速流失的小工具 下载地址:https://www.linqpad.net/有免费版,基本功能已经够用。我们公司买了它的Premium版。

AngleSharp 代码实操

实操前一些分享一些C#的知识点

如何快速发送网络请求获取到数据呢?

可以用如下: 1、HttpWebRequest 2、WebClient 3、HttpClient 4、RestSharp 5、Flurl

本期重点用 HttpClient来实现

起手式

引用NuGet包: Install-PackageAngleSharp

使用场景案例

  1. 获取博客园排行榜的Html并且解析

  1. IConfiguration config = Configuration.Default.WithDefaultLoader();

  2. string address = "https://www.cnblogs.com/aggsite/SideRight";

  3. IBrowsingContext context = BrowsingContext.New(config);

  4. IDocument document = await context.OpenAsync(address);

  5. IHtmlCollection<IElement> side_right = document.QuerySelectorAll("div");

  6. side_right.Select(m => new {

  7.        title = m.QuerySelector(".card-title a")?.TextContent,

  8.        url = m.QuerySelectorAll("ul li").Select(x => x.TextContent)

  9.       })

  10.       .Where(x => x.title != null)

  11.       .Dump();

通过上面代码快速就能分析且快速抓取博客园的排行榜,简单,快速,高效 代码少,有没有觉得 Linq语法糖配合请求一些框架的强大呢,朋友们

效果图

既然都能抓取数据了,接下来就是爬虫最重要的分析啦

2.分析博客园每天什么时候发博客看的人数最多,点赞的人数最多,星期几发文章多,哪个大佬发文章多

获取数据的方法

通过HttpClient加上Linq加上AngleSharp实现请求获取Hmtl => 保存Json => 分析Json 生成有价值的图表

  1. public void GetData()

  2. {

  3. var http = new HttpClient();

  4. var parser = new HtmlParser();

  5. File.WriteAllText(@"C:\Users\QYM\Desktop\OfficFile\BlogData.json", JsonConvert.SerializeObject(Enumerable.Range(1, 200)

  6.     .AsParallel()

  7.     .AsOrdered()

  8.     .SelectMany(page =>

  9.     {

  10.      var content = new StringContent(JsonConvert.SerializeObject(new

  11.      {

  12.       CategoryId = "808",

  13.       CategoryType = "SiteHome",

  14.       ItemListActionName = "AggSitePostList",

  15.       PageIndex = $"{page}",

  16.       ParentCategoryId = "0",

  17.       TotalPostCount = "4000"

  18.      }), Encoding.UTF8, "application/json");

  19.      var resp = http.PostAsync("https://www.cnblogs.com/AggSite/AggSitePostList", content).Result;

  20.      var document = parser.ParseDocument(resp.Content.ReadAsStringAsync().GetAwaiter().GetResult());

  21.      return document?.QuerySelectorAll("article").Select(pageContext =>

  22.      {

  23.       return new

  24.       {

  25.        Url = pageContext.QuerySelector(".post-item-text a").GetAttribute("href").Trim(),

  26.        Title = pageContext.QuerySelector(".post-item-text a").TextContent.Trim(),

  27.        Context = pageContext.QuerySelector(".post-item-text p").TextContent.Trim(),

  28.        Name = pageContext.QuerySelector("footer a").TextContent.Trim(),

  29.        DateTime = DateTime.Parse(pageContext.QuerySelector("footer .post-meta-item").TextContent),

  30.        LookOK = pageContext.QuerySelector("footer .post-meta-item+a span").TextContent.Trim(),

  31.        LookPerson = pageContext.QuerySelector("footer .post-meta-item+a+a+a span").TextContent.Trim()

  32.       };

  33.      });

  34.     }), Newtonsoft.Json.Formatting.Indented));

  35. }

效果图

获取博客园200页数据

读取数据并且调用LinqPad 自带的Chart图表方法进行分析

  1. public void ReadData()

  2. {

  3. var data = JsonConvert.DeserializeObject<List<BlogJsonData>>(File.ReadAllText(@"C:\Users\QYM\Desktop\OfficFile\BlogData.json"));

  4. Util.Chart(data

  5. .GroupBy(x => x.DateTime.Hour)

  6. .Select(x => new { Hour = x.Key, ViewCount = 1.0 * x.Sum(v => v.LookPerson) })

  7. .OrderByDescending(x => x.Hour),

  8. x => x.Hour,

  9. y => y.ViewCount, Util.SeriesType.Bar).Dump("时间段观看人数最多");

  10. Util.Chart(data

  11. .GroupBy(x => x.DateTime.Hour)

  12. .Select(x => new { Hour = x.Key, ViewCount = 1.0 * x.Sum(v => v.LookOk) })

  13. .OrderByDescending(x => x.Hour),

  14. x => x.Hour,

  15. y => y.ViewCount, Util.SeriesType.Bar).Dump("时间段点赞人数最多");

  16. Util.Chart(data

  17.  .GroupBy(x => x.DateTime.DayOfWeek)

  18.  .Select(x => new { WeekDay = x.Key, ArticleCount = x.Count() })

  19.  .OrderBy(x => x.WeekDay),

  20. x => x.WeekDay.ToString(),

  21. y => y.ArticleCount, Util.SeriesType.Bar).Dump("星期几发文章最多");

  22. Util.Chart(data

  23.  .GroupBy(x => x.Name)

  24.  .Select(x => new { UserName = x.Key, ArticleCount = x.Count() })

  25.  .OrderByDescending(x => x.ArticleCount)

  26.  .Take(9),

  27. x => x.UserName,

  28. y => y.ArticleCount,  Util.SeriesType.Bar).Dump("哪个大佬发文章比较多");

  29. }

效果图

源文件Json


分析数据的实体

  1. public class BlogJsonData

  2. {

  3. public string Url { get; set; }

  4. public string Title { get; set; }

  5. public string Context { get; set; }

  6. public string Name { get; set; }

  7. public DateTime DateTime { get; set; }

  8. public int LookOk { get; set; }

  9. public int LookPerson {get;set;}

  10. }

接下来就是见证奇迹的时候,通过分析抓取到html,保存成Json分析出一些意想不到的图表

效果图

  1. 时间段观看人数最多? 

看来博客园一般查看人数最多的是9点->10点,说明哈哈哈,果然大家早上都是喜欢关注编程的大事呀

  1. 时间段点赞人数最多? 

果然早起的鸟儿有虫吃,如果想要博客点赞高,那就必须早上九点 -> 10点 抓住阅读高峰期,菜鸟收获高赞,得到很多人的认可

  1. 星期几发文章最多? 

看来星期一到星期五中发博客最多的星期一和星期二,最不想上班的两天最适合用来灵感创作写文字

  1. 哪个大佬发文章比较多? 

目测近期京东云开发者对博客园贡献很大,看了一下,质量都是很高的文章,极力推荐


用AngleSharp & LINQPad抓取分析博客园排行榜的评论 (共 条)

分享到微博请遵守国家法律