instagram-private-api 响应结构解析:TopicalExploreFeedResponseRichTextDescriptionItem 富文本描述接口详解

原创2026-10-15 18:34:551,429 阅读
文章标签:后端

instagram-private-api 响应结构解析:TopicalExploreFeedResponseRichTextDescriptionItem 富文本描述接口详解

本文围绕 instagram-private-api(NodeJS Instagram 私有 API SDK,TypeScript 编写)中探索页商品数据所携带的富文本描述结构展开。TopicalExploreFeedResponseRichTextDescriptionItem 定义了 Instagram 购物商品在 Topical Explore(话题探索)信息流中"富文本描述"的最小组成单元,包含段落块类型、嵌套深度与文本实体三部分。读完本文,你将掌握该接口的字段语义、它在完整响应对象树中的位置、如何通过 SDK 的 TopicalExploreFeed 拉取并解析这段富文本,以及如何基于源码级证据进行数据消费。

一、接口定位:探索信息流里的商品描述块

在 instagram-private-api 的响应类型体系中,TopicalExploreFeedResponseRichTextDescriptionItem 并非独立存在的顶层对象,而是作为商品对象描述的一部分被嵌套使用。从源码 src/responses/topical-explore.feed.response.ts 可以看到,它被挂在购物商品接口 TopicalExploreFeedResponseProduct 的可选属性 rich_text_description 上:

export interface TopicalExploreFeedResponseProduct {
    name: string;
    price: string;
    current_price: string;
    full_price: string;
    product_id: string;
    merchant: TopicalExploreFeedResponseMerchant;
    // ...
    rich_text_description?: TopicalExploreFeedResponseRichTextDescriptionItem[];
}

也就是说,一个商品可能携带一个富文本描述块数组,数组中的每一项就是一个 TopicalExploreFeedResponseRichTextDescriptionItem。该属性在文档中标注为 Optional,意味着并非所有商品都会返回富文本描述——在消费数据时需要做好为空或缺失的防御处理。

整个数据对象的嵌套链路可以概括为:

TopicalExploreFeedResponseRootObject
 └── sectional_items[](分区项)
      └── layout_content(布局内容,含 fill_items / medias 等)
           └── media(媒体对象)
                └── product_tags(商品标签)
                     └── in[] → product(商品)
                          └── rich_text_description[](富文本描述)
                               └── TopicalExploreFeedResponseRichTextDescriptionItem

二、接口字段详解:三个属性的完整语义

依据 接口文档 与源码定义(src/responses/topical-explore.feed.response.ts),该接口只有三个属性:

export interface TopicalExploreFeedResponseRichTextDescriptionItem {
    block_type: string;
    depth: number;
    text_with_entities: TopicalExploreFeedResponseText_with_entities;
}
属性 类型 说明
block_type string 富文本块的类型标识,用于区分不同的内容块(如段落、标题、项目符号等排版单元)
depth number 该块在富文本文档中的嵌套层级,用于表达列表层级、引用层级等嵌套关系
text_with_entities TopicalExploreFeedResponseText_with_entities 承载该块的纯文本内容及内联样式区间(实体)

三个属性中,block_type 与 depth 描述的是块级排版结构,而 text_with_entities 则是该块内部行内文本与样式的载体,三者共同组成一个完整的富文本段落单元。

block_type:块级排版标识

block_type: string 用于标记该内容块属于哪种排版类型。虽然 instagram-private-api 的接口定义将其声明为普通 string 而没有收敛为字面量联合类型,但从富文本渲染的常规语义推断,其取值一般对应段落、标题、引用、列表等块级元素类型。在编写渲染逻辑时,建议依据 block_type 分支处理不同块的展示方式,并预留默认兜底分支。

depth:嵌套层级

depth: number 表示该块在整篇富文本描述中的嵌套深度。当描述内容包含多级列表或层层嵌套的引用块时,depth 的数值会随层级递增。前端渲染时通常用它来换算缩进量(如 depth * N px),从而实现视觉上的层级区分。

text_with_entities:块内文本与样式实体

text_with_entities 是该接口唯一的嵌套对象属性,类型为 TopicalExploreFeedResponseText_with_entities,它承载着块内的实际文本内容和行内样式区间(详见下一节)。

三、嵌套结构:text_with_entities 与 inline_style_ranges

TopicalExploreFeedResponseText_with_entities 定义在 src/responses/topical-explore.feed.response.ts,结构如下:

export interface TopicalExploreFeedResponseText_with_entities {
    text: string;
    inline_style_ranges: TopicalExploreFeedResponseInlineStyleRangesItem[];
}
  • text: string:该块的实际纯文本内容,不含任何样式标记。
  • inline_style_ranges: TopicalExploreFeedResponseInlineStyleRangesItem[]:一个行内样式区间数组,用"偏移 + 长度 + 样式枚举"的方式描述文本中哪些子区间需要套用何种样式。这是一个典型的**区间标注(range annotation)**设计——文本本身是纯字符串,样式信息与文本分离存放,而不是内嵌 HTML 或 Markdown 标记。

每个区间项由 TopicalExploreFeedResponseInlineStyleRangesItem 描述(源码位于 src/responses/topical-explore.feed.response.ts):

export interface TopicalExploreFeedResponseInlineStyleRangesItem {
    inline_style: number;
    length: number;
    offset: number;
}
属性 类型 说明
inline_style number 行内样式枚举值,通常以数字标识加粗、斜体、下划线等具体样式
length number 样式区间的字符长度
offset number 样式区间在 text 字符串中的起始偏移量(从 0 开始)

因此,解析一段富文本的完整算法是:先取 text_with_entities.text 拿到纯文本,再遍历 inline_style_ranges,对每个区间按 offset 与 offset + length 切分文本,并为该子串应用 inline_style 对应的样式。

四、实战获取:通过 TopicalExploreFeed 拉取商品富文本描述

要真正拿到含 rich_text_description 的响应数据,需要借助 SDK 的探索信息流。TopicalExploreFeed 类实现于 src/feeds/topical-explore.feed.ts,其底层请求为 GET /api/v1/discover/topical_explore/,并通过 FeedFactory 对外暴露(src/core/feed.factory.ts)。

典型用法如下:

import { IgApiClient } from 'instagram-private-api';

(async () => {
  const ig = new IgApiClient();
  ig.state.generateDevice('你的设备型号');
  await ig.account.login('username', 'password');

  // 通过工厂方法创建 TopicalExploreFeed,可覆盖 clusterId / lat / lng / module 等参数
  const feed = ig.feed.topicalExplore({
    clusterId: 'explore_all:0',
    // lat: 31.23, lng: 121.47, // 可选:传入地理位置影响推荐
  });

  const items = await feed.items(); // 每个 item 为 TopicalExploreFeedResponseSectionalItemsItem
  for (const item of items) {
    const medias = item.layout_content.medias ?? item.layout_content.fill_items;
    for (const entry of medias ?? []) {
      const productTags = entry.media.product_tags?.in ?? [];
      for (const tag of productTags) {
        const product = tag.product;
        if (!product?.rich_text_description) continue;

        // 逐块解析富文本描述
        for (const block of product.rich_text_description) {
          const { block_type, depth, text_with_entities } = block;
          console.log(`[${block_type}] (depth=${depth})`);
          console.log('  text:', text_with_entities.text);
          for (const range of text_with_entities.inline_style_ranges) {
            console.log(
              `  style#${range.inline_style} @${range.offset}+${range.length}`,
            );
          }
        }
      }
    }
  }
})();

需要注意,TopicalExploreFeed 继承自 Feed<Response, Item> 基类(src/core/feed.ts),因此它还具备 isMoreAvailable()、items$/observable() 等能力,可用于翻页遍历更多探索内容;在遇到 400/429/500/502 等响应时,基类的 attemptOptions 会自动按退避策略重试。

分页与模块参数

从 src/feeds/topical-explore.feed.ts 的 request() 实现可以看到,该接口还支持以下查询参数:

  • max_id:翻页游标,由上一轮响应的 next_max_id 驱动;
  • module:默认 'explore_popular',用于标记信息流来源(IgAppModule 类型的取值全集见 src/types/common.types.ts);
  • cluster_id:默认 'explore_all:0',注释明确说明"修改它以切换信息流分类";
  • session_id:默认生成一个 UUID v4,用于会话追踪;
  • lat / lng:可选地理位置参数,影响推荐结果;
  • timezone_offset:取自 client.state.timezoneOffset。

五、富文本渲染与防御性消费建议

综合接口定义与源码证据,在实际项目中消费该数据结构时,有以下几条建议:

  1. 空值防御:rich_text_description 在 TopicalExploreFeedResponseProduct 上是可选属性,且 product_tags、product、layout_content.medias/fill_items 均为可空结构,遍历前务必做存在性判断;
  2. 按块渲染:以 block_type + depth 决定块级排版(标题、段落、列表缩进),以 text_with_entities.inline_style_ranges 计算行内样式区间;
  3. 区间切分:对每个 inline_style_ranges 项按 offset 与 length 对 text 做子串切分,避免样式越界;
  4. 文本与样式分离:text 是纯字符串,不要尝试在其中寻找 HTML/Markdown 标记,所有样式都通过区间表达;
  5. 保持类型兼容:若接口返回的枚举含义发生变化(如 inline_style 数字取值扩张),建议在渲染层建立枚举映射并为未知值提供兜底样式。

六、相关源码与文档索引

为便于继续深入阅读,这里汇总与本文相关的仓库资源:

通过以上源码与文档对照,你可以完整掌握 Instagram 探索信息流中商品富文本描述的数据形态,并据此实现合规、健壮的解析与渲染逻辑。

登录后查看全文
instagram-private-api