instagram-private-api 中 TagsFeedResponseUser 接口解析:标签话题流里的用户对象结构与实战用法
instagram-private-api 中 TagsFeedResponseUser 接口解析:标签话题流里的用户对象结构与实战用法
在 instagram-private-api 中,TagsFeedResponseUser 是标签(Hashtag)话题流响应里描述“某个用户”的核心接口。本文以 docs/interfaces/responses/TagsFeedResponseUser.md 文档为主体,结合 src/responses/tags.feed.response.ts 与 src/feeds/tags.feed.ts 的源码实现,讲清楚这个接口的每一个字段、它在标签流响应 JSON 中出现的四个位置,以及如何通过 ig.feed.tags() 发起请求、逐页拉取数据并把其中的用户对象安全地读取出来。读完后,你可以独立完成:构造标签话题流请求、解析分页响应、从媒体/评论/标签位置中安全提取用户信息。
TagsFeedResponseUser 接口定义与字段总览
TagsFeedResponseUser 定义于 src/responses/tags.feed.response.ts,是 responses 模块导出的接口之一(见 src/responses/index.ts 的 export * from './tags.feed.response')。官方文档 TagsFeedResponseUser.md 为其 10 个属性逐一给出了定义位置,本文将其汇总为完整字段表:
| 属性 | 类型 | 是否可选 | 定义位置 | 含义 |
|---|---|---|---|---|
pk |
number |
必填 | tags.feed.response.ts#L86 | 用户的数字主键(primary key),是后续按 ID 调用户/好友关系接口的关键标识 |
username |
string |
必填 | tags.feed.response.ts#L87 | 登录名(@ 后面的部分) |
full_name |
string |
必填 | tags.feed.response.ts#L88 | 用户显示名(昵称) |
is_private |
boolean |
必填 | tags.feed.response.ts#L89 | 该账号是否为私密账号 |
profile_pic_url |
string |
必填 | tags.feed.response.ts#L90 | 头像 URL,一般可直接用于前端展示 |
profile_pic_id |
string |
可选 | tags.feed.response.ts#L91 | 头像的图片资源 ID |
is_verified |
boolean |
可选 | tags.feed.response.ts#L92 | 是否经过认证(蓝 V) |
friendship_status |
TagsFeedResponseFriendship_status |
可选 | tags.feed.response.ts#L93 | 当前登录用户与目标用户的好友关系状态 |
has_anonymous_profile_picture |
boolean |
可选 | tags.feed.response.ts#L94 | 是否使用系统默认(匿名)头像 |
is_unpublished |
boolean |
可选 | tags.feed.response.ts#L95 | 账号是否处于“未公开”状态(如新注册未激活) |
is_favorite |
boolean |
可选 | tags.feed.response.ts#L96 | 是否为当前用户的特别关注 |
接口原始定义如下,注意 profile_pic_id、is_verified、friendship_status、has_anonymous_profile_picture、is_unpublished、is_favorite 均带 ? 可选标记,解析时必须做空值防御:
export interface TagsFeedResponseUser {
pk: number;
username: string;
full_name: string;
is_private: boolean;
profile_pic_url: string;
profile_pic_id?: string;
is_verified?: boolean;
friendship_status?: TagsFeedResponseFriendship_status;
has_anonymous_profile_picture?: boolean;
is_unpublished?: boolean;
is_favorite?: boolean;
}
嵌套的 friendship_status 结构
friendship_status 指向同文件中的 TagsFeedResponseFriendship_status,文档见 TagsFeedResponseFriendship_status.md:
export interface TagsFeedResponseFriendship_status {
following: boolean; // 当前登录用户是否已关注该用户
outgoing_request: boolean; // 当前登录用户是否已向该用户发出(待接受)关注请求
is_bestie: boolean; // 该用户是否在当前登录用户的亲密好友(Bestie)列表中
}
这组字段是“相对当前登录会话”的状态,也就是说:同一帖子、用不同账号登录拉取标签流,friendship_status 的内容会不同。做爬虫聚合时不要假设它恒定。
这个用户对象在哪里出现:标签流响应的四条挂载路径
TagsFeedResponseUser 并非标签流顶层字段,而是嵌在媒体对象内部。从源码结构看,在 src/responses/tags.feed.response.ts 中它共有 4 个引用位置,覆盖了“帖子、评论、文案、@ 提及”四类用户触点:
- 帖子作者 ——
TagsFeedResponseMedia.user(必填):话题下每条媒体(图文/视频/轮播)的作者信息,这是最主要的消费场景; - 预览评论作者 ——
TagsFeedResponsePreviewCommentsItem.user(必填):媒体上挂的热门预览评论的评论者; - 文案作者 ——
TagsFeedResponseCaption.user(必填):一般与帖子作者一致; - @ 提及用户 ——
TagsFeedResponseInItem.user(必填):通过usertags.in[]挂在媒体上,表示在该帖图片/视频中被 @ 的人,与position坐标(归一化的像素位置数组)配合使用。
整体响应树(根接口 TagsFeedResponse,定义见 src/responses/tags.feed.response.ts)可以概括为:
TagsFeedResponse
├─ sections: TagsFeedResponseSectionsItem[] // 按 layout_type 分块的板块
│ └─ layout_content.medias[].media
│ ├─ user: TagsFeedResponseUser // ① 帖子作者
│ ├─ preview_comments[].user // ② 预览评论作者
│ ├─ caption?.user // ③ 文案作者
│ └─ usertags?.in[].user // ④ 被 @ 的用户
├─ more_available: boolean // 是否还有下一页
├─ next_page: number
├─ next_media_ids: string[]
├─ next_max_id: string
└─ status: string
由于四个位置共用的都是同一个接口,前端渲染头像、昵称、认证标记时只需写一份取值逻辑即可覆盖“作者 / 评论者 / 被 @ 者”。
请求侧实现:TagsFeed 与 ig.feed.tags() 的完整调用链
理解用户对象后,再看它从哪个请求返回。instagram-private-api 约定所有分页端点以 Feed 形式暴露,客户端上的 ig.feed 是 FeedFactory(见 src/core/client.ts 的 public feed = new FeedFactory(this))。标签话题流对应工厂方法 tags:
public tags(tag: string, tab: 'top' | 'recent' | 'places' = 'top'): TagsFeed {
const feed = new TagsFeed(this);
feed.tag = tag;
feed.tab = tab;
return feed;
}
注意区分两个易混入口:ig.feed.tag(tag)(单数)返回 TagFeed 用于标签详情页媒体流;ig.feed.tags(tag, tab)(复数)返回 TagsFeed 用于“热门/最新/地点”三个标签板块,tab 取值 top | recent | places,默认 top。TagsFeedResponseUser 属于后者的响应类型。
TagsFeed.request():请求参数逐一说明
TagsFeed 继承自抽象基类 Feed,其 request() 方法对 Instagram 私有端点发起 POST 请求:
public async request() {
const { body } = await this.client.request.send<TagsFeedResponse>({
url: `/api/v1/tags/${encodeURI(this.tag)}/sections/`,
method: 'POST',
form: {
_csrftoken: this.client.state.cookieCsrfToken,
tab: this.tab,
_uuid: this.client.state.uuid,
session_id: this.client.state.clientSessionId,
page: this.nextPage,
next_media_ids: this.nextPage ? JSON.stringify(this.nextMediaIds) : void 0,
max_id: this.nextMaxId,
},
});
this.state = body;
return body;
}
关键参数解读(源码见 src/feeds/tags.feed.ts):
- URL:
/api/v1/tags/{tag}/sections/,tag 经encodeURI编码,因此含特殊字符的话题名也可以传入; _csrftoken/_uuid/session_id:分别从client.state的 Cookie CSRF token、设备 UUID 与客户端会话 ID 读取,是登录态会话的防伪三要素,调用方无需手工构造;tab:对应工厂方法传入的top|recent|places;page/next_media_ids/max_id:三个分页游标。首次请求时nextPage未定义,next_media_ids会显式传undefined(void 0);之后每页响应中的next_page、next_media_ids、next_max_id会写入内部状态供下一请求使用。
状态 setter:分页游标的写入
protected set state(body: TagsFeedResponse) {
this.moreAvailable = body.more_available;
this.nextMaxId = body.next_max_id;
this.nextPage = body.next_page;
this.nextMediaIds = body.next_media_ids;
}
moreAvailable 决定了 isMoreAvailable() 的返回值(见 src/core/feed.ts),也就是自动翻页与 RxJS 流的终止条件;三个游标字段都标了 @Expose() 装饰器,因此可以被 serialize() / deserialize() 持久化,实现“跨进程续页”。
items():只取 media_grid 板块中的媒体
public async items() {
const response = await this.request();
return flatten(
response.sections.map(section => {
if (section.layout_type !== 'media_grid') return;
return section.layout_content.medias.map(medias => medias.media);
}),
);
}
这里有一个容易被忽略的实现细节:响应里的 sections<a href="https://link.gitcode.com/i/b6bcf95523ebacd64b713e370356147f" target="_blank">] 可能包含多种 layout_type(从源码结构看,TagsFeedResponseSectionsItem 还携带 feed_type 与 explore_item_info,后者含 num_columns、total_num_columns、aspect_ratio、autoplay 等网格排版信息,定义见 [src/responses/tags.feed.response.ts),但 items() 只保留 layout_type === 'media_grid' 的板块,其余板块被丢弃后由 lodash flatten 拉平成一个 TagsFeedResponseMedia[] 数组。也就是说:items() 返回的是帖子数组(每条内含 user: TagsFeedResponseUser),而不是原始 section 结构;如果你需要完整的 section 级响应(包括非 grid 板块),应改用 feed.request() 直接拿 TagsFeedResponse。
实战:拉取话题流并提取用户对象
下面给出一个端到端示例,基于 README.md 的登录约定与 examples/account-followers.feed.example.ts 的 Feed 用法模式。它演示了 request() 与 items() 两种消费方式、自动翻页、状态序列化续页与 RxJS 流式订阅,并在每步中演示 TagsFeedResponseUser 的读取:
import 'dotenv/config';
import { IgApiClient } from 'instagram-private-api';
import { TagsFeedResponseMedia } from 'instagram-private-api/dist/responses';
(async () => {
const ig = new IgApiClient();
ig.state.generateDevice(process.env.IG_USERNAME);
ig.state.proxyUrl = process.env.IG_PROXY;
await ig.simulate.preLoginFlow();
const loggedInUser = await ig.account.login(process.env.IG_USERNAME, process.env.IG_PASSWORD);
// 1. 构造标签话题流:tab 支持 'top' | 'recent' | 'places',默认 'top'
const tagsFeed = ig.feed.tags('travel', 'recent');
// 2. 方式一:直接拿整段响应(能看到 sections、more_available、next_page 等原始字段)
const raw = await tagsFeed.request();
console.log(raw.status, raw.more_available, raw.next_page);
// 3. 方式二:只拿拉平后的媒体数组,作者即 TagsFeedResponseUser
const medias: TagsFeedResponseMedia[] = await tagsFeed.items();
const firstAuthor = medias[0].user;
console.log(
firstAuthor.pk,
firstAuthor.username,
firstAuthor.is_verified ?? false, // 可选字段,务必用 ?? 兜底
firstAuthor.friendship_status?.following, // 可选嵌套,需可选链
);
console.log('被 @ 的用户:',
medias[0].usertags?.in?.map(u => u.user.username) ?? []);
// 4. Feed 是有状态且自动分页的:连续调用 items() 即逐页获取
const nextPage = await tagsFeed.items();
// 5. 状态可序列化,供另一进程/时刻续页
const snapshot = tagsFeed.serialize();
tagsFeed.deserialize(snapshot);
// 6. 或用 RxJS 流一次性订阅所有页(内部自动 retry,遇到 400/429/500/502 会退避等待)
tagsFeed.items$.subscribe(
page => page.forEach(m => console.log(m.taken_at, m.user.username)),
error => console.error(error),
() => console.log('Complete!'),
);
})();
关于第 6 步的流式订阅,src/core/feed.ts 中基类默认重试策略为 maxAttempts: 10、minDelay: 60000、maxDelay: 300000(毫秒),且当响应状态码命中 400/429/500/502 且错误为 IgResponseError 时会继续等待而非中断(见 src/core/feed.ts)。这意味着 items$ 的“Complete”可能持续较久,做批量采集时应自行控制总量与速率,避免对私有 API 形成高频访问。
解析用户对象时的防御要点
综合字段表与四条挂载路径,解析 TagsFeedResponseUser 时建议遵循三条规则:
- 必填四元组直接取:
pk、username、full_name、profile_pic_url是渲染“作者卡片”的最低集合; - 可选布尔一律
?? false:is_verified、has_anonymous_profile_picture、is_unpublished、is_favorite未返回不代表为假,接口标注为 Optional; friendship_status用可选链访问:它是“相对登录会话”的状态,服务端可能不下发;聚合多账号数据时应明确记录该字段对应的会话身份。
另外提醒:is_private: true 只表示该账号是私密账号,并不代表话题流里的这条媒体本身不可见——该媒体仍会随其所属话题展示,只是你不能像查看公开主页那样直接浏览其全部作品。
小结
TagsFeedResponseUser 是 instagram-private-api 标签话题流(TagsFeed)响应中“用户”这一维度的统一契约:10 个字段(4 必填 + 6 可选)加上可选的 friendship_status 嵌套结构,足以支撑作者展示、认证标记、关注关系判断等常见需求。它的消费链路是 ig.feed.tags(tag, tab) → TagsFeed.request() 以 page / next_media_ids / max_id 三游标自动翻页 → items() 过滤出 media_grid 板块 → 从 media.user、preview_comments[].user、caption.user、usertags.in[].user 四个位置读取用户对象。相关文档可继续沿 TagsFeedResponseUser.md、TagsFeedResponse.md 与 responses 模块索引 深入其他同族接口。