You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python代码中实现列表嵌套存储Instagram爬虫评论

解决Instagram爬虫评论嵌套列表存储问题

完全懂这种连续熬两天开发后的脑子卡壳!明明是简单的结构调整,但就是一时转不过弯来,我帮你捋清楚~

问题核心

你当前的代码是把所有帖子的评论都塞进同一个一维列表,导致所有评论混在一起。要实现按帖子分组的嵌套列表,关键是为每个帖子创建独立的子列表,处理完单个帖子后再将子列表存入主列表。

修改后的代码

# 修正变量名(遵循PEP8规范:小写加下划线)
post_links = ['https://www.instagram.com/p/BesW08pHfUt', 'https://www.instagram.com/p/BQZyTtej4yj']
# 初始化主列表,用于存储每个帖子的评论子列表
all_post_comments = []

for post_link in post_links:
    # 为当前帖子创建专属的评论子列表
    post_comments = []
    # 获取当前帖子的评论数据
    _ = API.getMediaComments(get_media_id(post_link), max_id=100)
    # 遍历评论并添加到子列表
    for c in reversed(API.LastJson['comments']):
        post_comments.append(c["user"]["username"])
    # 将当前帖子的评论子列表存入主列表
    all_post_comments.append(post_comments)

效果验证

运行后,all_post_comments的输出就是你期望的嵌套结构:

[['headhotel', 'famegalore', 'motivationpoem', 'malicioussatan'], ['monarch_motivation', 'headhotel', 'motivationpoem']]

小提示

如果某个帖子没有抓取到评论,对应的子列表会是空的[],这样能保证整个嵌套列表的结构一致性,避免后续处理时出现数据错位问题。

内容的提问来源于stack exchange,提问作者Rajas Rasam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:09:58