求助:通过Facebook Graph API获取帖子缺失指标
获取Facebook单帖剩余指标的解决方案
核心问题说明
你之前调用的/{page-ID}/insights是主页级别的汇总统计接口,返回的是整个主页在时间范围内的总数据,而非单条帖子的指标。要获取单帖的对应指标,需要针对每个帖子的ID单独调用insights接口,并指定单帖维度的统计参数。
步骤与具体实现
1. 先获取目标时间段内的所有帖子(含ID)
在原有的feed接口中,确保拿到每个帖子的id字段(默认会返回,若有自定义字段需显式包含):
import requests page_id = "你的主页ID" start_date = "起始Unix时间" end_date = "结束Unix时间" access_token = "你的访问令牌" # 拉取帖子列表(含基础字段及帖子ID) feed_url = f"https://graph.facebook.com/v15.0/{page_id}/feed?fields=id,message,created_time,comments.summary(true),reactions.limit(1).summary(true),shares&since={start_date}&until={end_date}&access_token={access_token}" response = requests.get(feed_url) posts = response.json().get("data", [])
2. 针对每个帖子ID拉取单帖insights指标
先明确你需要的剩余指标对应的Facebook API官方指标名称,再调用单帖级别的insights接口:
| 你需要的指标 | API对应指标名称 |
|---|---|
| 链接点击量 | post_clicks_link |
| 其他点击量 | post_clicks_other |
| 浏览量(总曝光) | post_impressions |
| 负面点击量 | post_negative_feedback |
| 自然触达量 | post_impressions_organic |
| 付费触达量 | post_impressions_paid |
示例代码:
# 定义需要获取的单帖指标集合 post_metrics = "post_clicks_link,post_clicks_other,post_impressions,post_negative_feedback,post_impressions_organic,post_impressions_paid" for post in posts: post_id = post["id"] # 调用单帖insights接口,指定生命周期累计数据 insights_url = f"https://graph.facebook.com/v15.0/{post_id}/insights?metric={post_metrics}&period=lifetime&access_token={access_token}" insights_response = requests.get(insights_url) insights_data = insights_response.json().get("data", []) # 将指标值整合到原帖子数据中 for metric in insights_data: post[metric["name"]] = metric["values"][0]["value"] # 此时post字典已包含所有你需要的指标 print(post)
关键参数说明
period=lifetime:表示获取帖子从发布到当前的累计数据,匹配你按时间段拉取帖子后统计单帖全量指标的需求。- 由于是针对单个帖子ID调用insights,默认就是单帖维度统计,无需额外指定
level=post参数。
内容的提问来源于stack exchange,提问作者Jesus Garcia
相关产品推荐
相关产品推荐

