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

能否通过YouTube Analytics API按视频+日期维度聚合获取数据?

问题描述

我有一个YouTube频道,想通过YouTube Analytics API提取频道内各视频的每日聚合数据(包括点赞、点踩、播放量、订阅数变化、观看时长等),但遇到两个问题:

  • 在API Explorer中同时选择day和video维度时,系统提示查询不支持;仅使用day维度能正常返回数据。
  • 用Python调用API时报错,错误信息为:Could not parse content (N/A) of field parameters.filters.

附上调用代码:

import googleapiclient.errors
import os
from googleapiclient.discovery import build
import google_auth_oauthlib.flow
from google.auth.transport.requests import Request

scopes = ["https://www.googleapis.com/auth/youtube.readonly"]

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    #os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtubeAnalytics"
    api_version = "v2"
    client_secrets_file = "supercliente.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube_analytics = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube_analytics.reports().query(
        dimensions="day,video",
        endDate="2022-05-01",
        ids="channel==MINE",
        maxResults=50,
        metrics="likes",
        startDate="2021-03-01",
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

报错详情:

HttpError: <HttpError 400 when requesting https://youtubeanalytics.googleapis.com/v2/reports?dimensions=day&endDate=2022-05-01&ids=channel%3D%3DMINE&maxResults=50&metrics=likes&startDate=2021-03-01&filters=vBDX3bljsGw&alt=json returned "Could not parse content (N/A) of field parameters.filters.". Details: "[{'message': 'Could not parse content (N/A) of field parameters.filters.', 'domain': 'global', 'reason': 'badRequest'}]">
解决方案

核心问题:维度组合限制

YouTube Analytics API不支持day和video直接组合作为维度。要获取单视频的每日数据,必须分两步操作:

  1. 先通过YouTube Data API获取频道内所有视频的ID列表。
  2. 针对每个视频ID,单独使用day维度+video过滤器查询每日数据。

修复API调用错误

你遇到的filters参数错误是因为请求中混入了无效格式的过滤器值(从请求URL能看到filters=vBDX3bljsGw,正确格式应该是video=={视频ID})。下面是完整的可运行代码:

修改后的示例代码
import googleapiclient.errors
import os
import time
from googleapiclient.discovery import build
import google_auth_oauthlib.flow
from google.auth.transport.requests import Request

# 需要同时申请YouTube Data API和YouTube Analytics API的权限
scopes = [
    "https://www.googleapis.com/auth/youtube.readonly",
    "https://www.googleapis.com/auth/yt-analytics.readonly"
]

def get_channel_video_ids(youtube_data_client):
    # 获取频道的上传列表ID
    channel_info = youtube_data_client.channels().list(
        mine=True,
        part="contentDetails"
    ).execute()
    uploads_playlist_id = channel_info["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]
    
    # 遍历上传列表,获取所有视频ID
    video_ids = []
    next_page_token = None
    while True:
        playlist_items = youtube_data_client.playlistItems().list(
            playlistId=uploads_playlist_id,
            part="contentDetails",
            maxResults=50,
            pageToken=next_page_token
        ).execute()
        
        video_ids.extend([item["contentDetails"]["videoId"] for item in playlist_items["items"]])
        next_page_token = playlist_items.get("nextPageToken")
        
        if not next_page_token:
            break
    return video_ids

def main():
    # 本地调试时可取消注释下面一行,生产环境必须删除
    # os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    client_secrets_file = "supercliente.json"
    
    # 获取OAuth凭证
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    
    # 初始化两个API客户端
    youtube_data = build("youtube", "v3", credentials=credentials)
    youtube_analytics = build("youtubeAnalytics", "v2", credentials=credentials)
    
    # 获取频道所有视频ID
    video_ids = get_channel_video_ids(youtube_data)
    
    # 逐个查询视频的每日数据
    for video_id in video_ids:
        try:
            analytics_request = youtube_analytics.reports().query(
                dimensions="day",
                endDate="2022-05-01",
                ids="channel==MINE",
                maxResults=100,
                # 这里可以添加你需要的所有指标
                metrics="likes,dislikes,views,subscribersGained,subscribersLost,watchTime",
                startDate="2021-03-01",
                filters=f"video=={video_id}"
            )
            response = analytics_request.execute()
            print(f"=== 视频 {video_id} 每日数据 ===")
            print(response)
            # 可在这里添加数据保存逻辑,比如写入CSV
            time.sleep(1)  # 避免触发API限流
        except googleapiclient.errors.HttpError as e:
            print(f"查询视频 {video_id} 失败: {e}")

if __name__ == "__main__":
    main()
注意事项
  • 确保在Google Cloud Console中已经启用YouTube Data API v3和YouTube Analytics API,否则会触发权限错误。
  • 若频道内视频数量较多,建议加入延迟(如示例中的time.sleep(1))避免触发API限流。
  • 支持的指标(metrics)和维度(dimensions)可参考官方API参数列表,根据需求调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:48:20