c# 基于Titanium爬取微信公众号历史文章列表

C# 基于Titanium爬取微信公众号历史文章列表攻略

1. 准备工作

1.1 安装Titanium

Titanium是一款爬虫框架,需要使用C#编写,因此在开始之前需要确保您已经安装了Titanium。您可以在Titanium官网下载最新版的Titanium,并根据其安装说明进行安装。

1.2 获取微信公众号的cookie

我们需要使用微信公众号的cookie来进行爬取。您可以使用您的微信账号登录公众号并手动保存cookie,也可以使用模拟登录获取cookie。以下为使用模拟登录获取cookie的示例代码:

using System;
using System.Net;
using System.Text;
using System.Web;
using System.IO;

namespace WeChatCrawler
{
    public class WeChatLogin
    {
        private static string wechatAccount = "your_wechat_account";
        private static string wechatPassword = "your_wechat_password";

        private static CookieContainer cookieContainer = new CookieContainer();

        public static void Login()
        {
            string loginUrl = "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=startlogin";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.CookieContainer = cookieContainer;

            string postData = string.Format("username={0}&pwd={1}&imgcode=&f=json&userlang=zh_CN&redirect_url=&token=&lang=zh_CN", wechatAccount, wechatPassword);

            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = byteArray.Length;
            Stream loginStream = request.GetRequestStream();
            loginStream.Write(byteArray, 0, byteArray.Length);
            loginStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
            response.Close();

            Console.WriteLine("微信公众号登录成功!");
        }

        public static CookieContainer GetCookieContainer()
        {
            return cookieContainer;
        }
    }
}

2. 爬取历史文章列表

2.1 获取公众号的__biz参数

在开始爬取微信公众号的历史文章列表之前,您需要先获取公众号的__biz参数。您可以通过浏览器的开发者工具,或者通过抓包工具获取。以下为使用模拟登录获取__biz参数的示例代码:

private static string GetBiz()
{
    string bizUrl = "https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token=&lang=zh_CN";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(bizUrl);
    request.Method = "GET";
    request.CookieContainer = WeChatLogin.GetCookieContainer();

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream responseStream = response.GetResponseStream();
    StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
    string responseData = streamReader.ReadToEnd();
    streamReader.Close();

    string bizPattern = @"<script id=""microbar"" type=""text/html"">([\s\S]*?)</script>";
    Match bizMatch = Regex.Match(responseData, bizPattern);
    string bizData = HttpUtility.HtmlDecode(bizMatch.Groups[1].Value);

    string biz = "";
    biz = Regex.Match(bizData, @"<a href=""/cgi-bin/menu/menu_manage\?t=menu/index&action=menu_edit&[\s\S]*?&biz=(?<biz>.*?)&[\s\S]*?"">").Groups["biz"].Value;

    Console.WriteLine("公众号biz参数获取成功:{0}", biz);

    return biz;
}

2.2 构建请求URL和POST数据

在获取__biz参数之后,您需要构建请求URL和POST数据来获取历史文章列表。以下为请求URL和POST数据的示例代码:

private static string BuildUrl(string biz, int offset, int count)
{
    string baseUrl = "https://mp.weixin.qq.com/cgi-bin/appmsg?action=list_ex";
    string postData = string.Format("type=9&query=&is_only_read=1&is_include_edu=1&is_include_old=1&is_include_ad=1&begin={0}&count={1}&fakeid={2}&token=&lang=zh_CN", offset, count, biz);

    return baseUrl + "&" + postData;
}

2.3 发送请求并解析返回结果

最后,您需要发送请求并解析返回结果来获取历史文章列表。以下为发送请求并解析返回结果的示例代码:

private static List<Article> GetArticles(string biz)
{
    List<Article> articles = new List<Article>();

    int offset = 0;
    int count = 10;
    int maxCount = 100;

    while (count <= maxCount)
    {
        string getUrl = BuildUrl(biz, offset, count);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
        request.Method = "GET";
        request.CookieContainer = WeChatLogin.GetCookieContainer();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();
        StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
        string responseData = streamReader.ReadToEnd();
        streamReader.Close();

        JObject jsonResult = JObject.Parse(responseData);

        JToken articleList = jsonResult["app_msg_list"];
        foreach (var articleItem in articleList)
        {
            Article article = new Article();
            article.Title = articleItem["title"].ToString();
            article.Url = articleItem["link"].ToString();
            article.PubTime = long.Parse(articleItem["create_time"].ToString());
            articles.Add(article);
        }

        if (maxCount == count || articleList.Count() <= 0)
        {
            break;
        }

        offset += count;
        count = maxCount - offset;
        if (count > 20)
        {
            count = 20;
        }
    }

    return articles;
}

3. 示例说明

3.1 示例1:获取公众号为“网易”(biz为“MjM5NTMxMTQ2MA==”)的历史文章列表

static void Main(string[] args)
{
    WeChatLogin.Login();

    string biz = "MjM5NTMxMTQ2MA==";
    List<Article> articles = GetArticles(biz);

    Console.WriteLine("网易公众号历史文章列表:");
    foreach (var article in articles)
    {
        Console.WriteLine("{0}({1}):{2}", article.Title, TimestampToDateTime(article.PubTime), article.Url);
    }

    Console.ReadLine();
}

3.2 示例2:获取公众号为“人民网”(biz为“MjM5NTY5MTE0MA==”)的历史文章列表

static void Main(string[] args)
{
    WeChatLogin.Login();

    string biz = "MjM5NTY5MTE0MA==";
    List<Article> articles = GetArticles(biz);

    Console.WriteLine("人民网公众号历史文章列表:");
    foreach (var article in articles)
    {
        Console.WriteLine("{0}({1}):{2}", article.Title, TimestampToDateTime(article.PubTime), article.Url);
    }

    Console.ReadLine();
}

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:c# 基于Titanium爬取微信公众号历史文章列表 - Python技术站

(0)
上一篇 2023年5月31日
下一篇 2023年5月31日

相关文章

  • 浅谈AjaxPro.dll,asp.net 前台js调用后台方法

    让我们来详细讲解一下“浅谈AjaxPro.dll,asp.net 前台js调用后台方法”的完整攻略。 什么是AjaxPro.dll AjaxPro.dll 是一个开源的 asp.net AJAX 库,可以帮助我们轻松地实现前台 js 和后台方法的调用,简化了前后台的交互。它特别适用于需要频繁异步交互、需要处理大量数据量的 web 应用程序。 AjaxPro.…

    C# 2023年6月3日
    00
  • c# 文件压缩zip或将zip文件解压的方法

    请看下面的详细讲解: 1. c# 文件压缩zip的方法 1.1 引用System.IO.Compression和System.IO.Compression.FileSystem命名空间 using System.IO.Compression; using System.IO.Compression.FileSystem; 1.2 创建压缩文件方法 // 压缩…

    C# 2023年6月1日
    00
  • JetBrains Rider 2021.1.0 安装激活方法详解 汉化补丁安装教程 真实有效

    下面就来详细讲解“JetBrains Rider 2021.1.0 安装激活方法详解 汉化补丁安装教程 真实有效”的完整攻略。 一、下载和安装JetBrains Rider 2021.1.0 下载JetBrains Rider 2021.1.0 首先,在官网下载JetBrains Rider 2021.1.0的安装包,官方下载地址:https://www.j…

    C# 2023年5月31日
    00
  • 深入探究ASP.NET Core Startup初始化问题

    深入探究 ASP.NET Core Startup 初始化问题 在 ASP.NET Core 中,Startup 类是应用程序的入口点,它负责配置应用程序的服务和中间件。本攻略将深入探究 ASP.NET Core Startup 初始化问题,包括 Startup 类的构造函数、ConfigureServices 方法和 Configure 方法。 Start…

    C# 2023年5月17日
    00
  • ext combobox动态加载数据库数据(附前后台)

    下面是详细的“ext combobox动态加载数据库数据(附前后台)”攻略。 什么是 ext combobox? ext combobox 是一种基于 ExtJS 框架开发的下拉菜单组件,它可以非常方便的实现下拉菜单的各种交互功能,同时也可以动态加载数据库数据实现自动填充下拉列表。 ext combobox 动态加载数据库数据操作步骤 创建数据库表 我们需要…

    C# 2023年5月31日
    00
  • ASP.NET性能优化小结(ASP.NET&C#)

    针对你提出的主题“ASP.NET性能优化小结(ASP.NET&C#)”,我将为你提供一些完整攻略,并附带两个示例,以供参考。 标题 1. 概述 对于一个高效的 ASP.NET 网站,性能优化至关重要。性能优化可以提高网站的访问速度、降低响应时间,缩短页面加载时间,减轻服务器的压力和消耗等。在本文中,我们将分享几个优化网站性能的策略。 2. 启用缓存(…

    C# 2023年5月15日
    00
  • C#中Dictionary排序方式的实现

    下面我将为您详细讲解如何在C#中使用Dictionary进行排序。 1. Dictionary排序的基本原理 C#中的Dictionary是一种键值对集合,其中TKey为键类型,TValue为值类型。在默认情况下,Dictionary按照键的默认顺序进行排序,并且不支持按照值排序。但是,我们可以通过以下两种方式来实现Dictionary的排序: 自定义比较器…

    C# 2023年6月1日
    00
  • ASP.NET Core文件上传与下载实例(多种上传方式)

    ASP.NET Core 文件上传与下载实例 在 ASP.NET Core 中,可以使用多种方式实现文件上传和下载。本攻略将详细介绍如何在 ASP.NET Core 中实现文件上传和下载,并提供多种上传方式的示例。 文件上传 单文件上传 在 ASP.NET Core 中,可以使用 IFormFile 接口实现单文件上传。以下是一个简单的单文件上传示例: [H…

    C# 2023年5月17日
    00
合作推广
合作推广
分享本页
返回顶部