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

使用Facebook Graph API获取帖子/视频/Reel每日指标遇问题求助

Facebook Graph API 获取内容每日指标问题及解决方案建议

问题背景

需要从内容创建日期起,获取Facebook帖子、视频、Reel的每日指标(曝光量、互动量、视频播放量等),但使用Graph API v20.0及更高版本时,返回的是累计或错误数据,而非单日独立数值。

已尝试操作

  • 刷新访问令牌:实现令牌刷新逻辑,确保始终使用有效访问令牌
  • 每日获取指标:通过insights端点指定period=day请求指标,但结果为累计或不完整数据

代码片段

1. 访问令牌刷新逻辑

import requests
from config import ACCESS_TOKEN, API_VERSION, CLIENT_ID, CLIENT_SECRET

def refresh_access_token():
    """Refresh the access token to get a new long-lived token."""
    refresh_url = f"https://graph.facebook.com/{API_VERSION}/oauth/access_token"
    params = {
        'grant_type': 'fb_exchange_token',
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'fb_exchange_token': ACCESS_TOKEN,
    }

    response = requests.get(refresh_url, params=params)
    if response.status_code == 200:
        data = response.json()
        new_access_token = data.get('access_token')
        if new_access_token:
            print("New token obtained:", new_access_token)
            with open('access_token.txt', 'w') as token_file:
                token_file.write(new_access_token)
            return new_access_token
    else:
        raise Exception(f"Error refreshing token: {response.status_code} - {response.text}")

2. 获取帖子每日指标逻辑

def fetch_daily_metrics(post_id, metrics, start_date, end_date):
    token = get_access_token()
    insights_url = f"https://graph.facebook.com/v20.0/{post_id}/insights"
    params = {
        'metric': ','.join(metrics),
        'access_token': token,
        'period': 'day',
        'since': start_date,
        'until': end_date,
    }

    response = requests.get(insights_url, params=params)
    if response.status_code == 200:
        return response.json().get('data', [])
    else:
        print(f"Error fetching metrics: {response.status_code}")
        print(response.text)
        return None

3. 指标数据上传至Google Sheets

import pandas as pd
from google_sheets import upload_to_google_sheets

def process_and_upload_metrics(metrics_data):
    rows = []
    for metric in metrics_data:
        name = metric['name']
        for value in metric.get('values', []):
            rows.append({'Date': value['end_time'], 'Metric': name, 'Value': value['value']})

    df = pd.DataFrame(rows).pivot_table(index='Date', columns='Metric', values='Value').reset_index()
    upload_to_google_sheets(df, "Facebook Insights", "Daily Metrics")

当前核心问题

  1. 指标数据累计:期望单日数值却得到累计数据,如何确保API返回单日独立数值?
  2. 数据不匹配:部分指标与Facebook UI洞察数据不一致。
  3. API版本选择:已测试v15.0至v21.0,哪个版本更适合获取每日指标?

解决方案建议

针对“指标数据累计”问题

  • 确认指标类型:部分Facebook指标本身为累计型(如total_impressions),需选择单日增量型指标,例如impressions_day(注意帖子、视频、Reel的指标命名存在差异,需对应内容类型选择)
  • 严格控制时间范围:将since和until设置为同一天(格式YYYY-MM-DD),避免跨天请求导致的累计;同时注意API返回的end_time为UTC时间,需转换为账号所在时区后再处理
  • 内容类型适配:Reel和视频需使用专属洞察指标,例如Reel的reel_plays需确保请求的是Reel的ID而非普通帖子ID,且指定period=day
  • 添加breakdown参数:若需更精细的单日数据,可尝试添加breakdown=day参数(部分指标支持)

针对“数据不匹配”问题

  • 时区统一:Facebook UI默认使用账号时区,API默认返回UTC时间,需将API数据转换为账号时区后再与UI数据对比
  • 指标定义对齐:核对API指标与UI指标的官方定义,例如UI中的“视频播放量”对应API的video_plays(单次播放)而非total_video_plays(累计播放时长对应的次数)
  • 延迟获取数据:Facebook洞察数据存在24-48小时的延迟,避免获取当天未完成的数据,建议次日获取前一天的指标

针对“API版本选择”问题

  • 优先使用v18.0至v20.0:这些版本的洞察端点稳定性高,全面支持帖子、视频、Reel的单日指标,且未出现大范围的累计数据逻辑调整
  • 避免使用v15.0及更早版本:旧版本已进入淘汰周期,对Reel等新内容类型的指标支持不全
  • 谨慎使用v21.0:该版本对部分洞察指标的计算逻辑进行了调整,可能导致累计数据问题,需先小范围测试验证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 17:43:15