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

如何通过Instagram API获取CAROUSEL_ALBUM的图片/视频及多条recent_media

解决方案

轮播相册子资源获取失效问题

原因:Instagram Graph API的hashtag/recent_media接口不支持直接嵌套查询children字段,你在请求参数的fields中写children{xxx}不会返回对应内容,属于接口设计限制。
解决方法:

  • 先从返回的列表中判断单条内容的media_type是否为CAROUSEL_ALBUM
  • 若是,单独发起请求调用/{post_id}/children端点,携带需要的media_type,media_url,thumbnail_url字段,即可拿到所有轮播子项,取第一条即可
  • 若该接口请求失败,直接取该轮播内容本身的media_url作为降级方案
  • 需确认你的Access Token具备instagram_basic权限,且应用已完成对应权限审核,测试模式下会出现字段返回不全的情况

recent_media仅返回1条问题

原因:该接口默认返回条数为1,需要主动添加limit参数指定返回数量。
解决方法:

  • 在请求参数中添加limit字段,最大值可设为50,即可一次返回最多50条最近内容
  • 若需要超过50条内容,可通过返回结果中paging.next的链接进行翻页查询
调整后代码示例
from define_insta import getCreds, makeApiCall

def get_carousel_children(post_id, params):
    # 单独请求轮播子资源
    endpointParams = {
        'fields': 'media_type,media_url,thumbnail_url',
        'access_token': params['access_token']
    }
    url = params['endpoint_base'] + '/' + post_id + '/children'
    res = makeApiCall(url, endpointParams, params['debug'])
    return res['json_data'].get('data', [])

def hashtagMedia(params):
    endpointParams = dict()
    endpointParams['user_id'] = params['instagram_account_id']
    # 移除原fields中的children嵌套查询
    endpointParams['fields'] = 'id,caption,comment_count,like_count,media_type,media_url,permalink'
    endpointParams['access_token'] = params['access_token']
    # 新增limit参数,最多返回50条
    endpointParams['limit'] = 50
    url = params['endpoint_base'] + '/' + params['hashtag_id'] + '/' + params['type']
    print(url)
    return makeApiCall(url, endpointParams, params['debug'])

# 调用示例
print("\n ------------ Recents -------------\n")
params = getCreds() 
params['type'] = 'recent_media'
hashtagRecentMediaResponse = hashtagMedia(params)
for post in hashtagRecentMediaResponse['json_data']['data']:
    print("\nlink to post: ")
    print(post['permalink'])
    print("\nPost Caption: ")
    print(post.get('caption', ''))
    print("\nMedia type: ")
    print(post['media_type'])
    
    if post['media_type'] == 'CAROUSEL_ALBUM':
        children = get_carousel_children(post['id'], params)
        if children:
            first_child = children[0]
            print("\n首条子资源媒体类型:")
            print(first_child['media_type'])
            print("\n首条子资源媒体链接:")
            print(first_child.get('media_url') or first_child.get('thumbnail_url'))
        # 降级逻辑:子资源获取失败时取相册本身的media_url
        else:
            print("\n媒体链接:")
            print(post['media_url'])
    else:
        print("\n媒体链接:")
        print(post['media_url'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:36:03