knowhow.md 11.5 KB

YouTube Data API v3 技术知识手册

版本: 1.0.0 更新日期: 2026-04-01 来源: Digester 整理 Hunter 调研数据


1. API 概述

1.1 基础信息

属性 值
端点 https://www.googleapis.com/youtube/v3
协议 HTTPS only
响应格式 JSON
认证方式 API Key (公开数据) / OAuth 2.0 (私有数据)
每日配额 10,000 units

1.2 核心端点

端点 用途 配额成本
GET /videos 获取视频详情 + 热门视频 1 unit
GET /videoCategories 获取地区可用分类 1 unit
GET /i18nRegions 获取支持地区列表 1 unit
GET /search 搜索视频/频道/播放列表 100 units ⚠️

关键洞察: videos.list + chart=mostPopular 是获取热门视频最配额友好的方式,比 search.list 便宜 100 倍。


2. 认证方式

2.1 API Key 认证 (推荐用于公开数据)

GET /videos?key={YOUR_API_KEY}&part=snippet&chart=mostPopular

获取步骤:

  1. 访问 Google Cloud Console
  2. 创建项目或选择现有项目
  3. 启用 YouTube Data API v3
  4. 创建凭据 → API 密钥
  5. (可选)限制密钥使用范围

2.2 OAuth 2.0 (用于私有数据/写入操作)

仅在需要访问用户私有数据或执行写入操作时使用。


3. 关键参数详解

3.1 chart 参数

值 说明
mostPopular 获取指定地区的热门视频列表
GET /videos?chart=mostPopular&regionCode=US&key={API_KEY}

3.2 part 参数

控制返回的字段集合,多值用逗号分隔:

Part 包含字段
snippet title, description, channelTitle, thumbnails, publishedAt, tags, categoryId
statistics viewCount, likeCount, commentCount, favoriteCount
contentDetails duration, dimension, definition, caption

推荐组合: part=snippet,statistics,contentDetails

3.3 regionCode 参数

ISO 3166-1 alpha-2 国家代码:

代码 国家/地区
US United States
JP Japan
KR South Korea
GB United Kingdom
DE Germany
FR France
IN India
BR Brazil
RU Russia
CN China (港澳台可用,大陆受限)

支持 50+ 个国家/地区,可通过 i18nRegions.list 获取完整列表。

3.4 videoCategoryId 参数

视频分类 ID (全球通用):

ID 分类
1 Film & Animation
2 Autos & Vehicles
10 Music
17 Sports
20 Gaming
22 People & Blogs
23 Comedy
24 Entertainment
25 News & Politics
27 Education
28 Science & Technology
42 Shorts
GET /videos?chart=mostPopular&regionCode=US&videoCategoryId=10&key={API_KEY}

3.5 maxResults 参数

  • 范围: 1-50
  • 默认值: 5
  • 推荐值: 50 (单次获取最大数量)

4. 配额管理策略

4.1 配额规则

指标 数值
默认每日配额 10,000 units
videos.list 单次成本 1 unit
chart=mostPopular 附加成本 0
regionCode 附加成本 0
videoCategoryId 附加成本 0
单次最大返回 50 条视频

4.2 每日理论上限

10,000 units × 50 videos/unit = 500,000 条视频/天

4.3 配额优化策略

  1. 批量获取: 使用 maxResults=50 最大化单次请求收益
  2. 避免搜索: search.list 消耗 100 units,优先使用 videos.list
  3. 本地缓存: Trending 数据 15-30 分钟内不会大幅变化
  4. 智能调度: 根据优先级获取不同地区/分类数据

4.4 配额监控

响应头包含配额信息:

X-Quota-User-Limit: 10000
X-Quota-User-Remaining: 9999

5. 错误处理最佳实践

5.1 完整错误码映射

HTTP 错误原因 触发场景 处理建议
400 badRequest 参数错误、无效 regionCode 校验参数后再请求
403 accessNotConfigured API Key 未关联 YouTube API 在 GCP 启用 API
403 quotaExceeded 每日配额耗尽 等待次日重置或申请提升
403 forbidden Key 受限、需要 OAuth 检查 Key 权限
404 notFound 资源不存在 跳过该资源
429 rateLimitExceeded 请求频率过高 指数退避重试

5.2 关键区别

⚠️ 配额耗尽返回 403,不是 429

  • 429 = 速度太快 → 缓一缓再试 (指数退避)
  • 403 quotaExceeded = 今天没额度 → 只能等明天

5.3 指数退避实现

import time
import random

def exponential_backoff(attempt):
    """计算退避时间"""
    base_delay = 1  # 秒
    max_delay = 60  # 秒
    delay = min(base_delay * (2 ** attempt) + random.uniform(0, 1), max_delay)
    return delay

def api_call_with_retry(func, max_retries=3):
    """带重试的 API 调用"""
    for attempt in range(max_retries):
        try:
            return func()
        except RateLimitError:
            if attempt < max_retries - 1:
                delay = exponential_backoff(attempt)
                time.sleep(delay)
            else:
                raise

5.4 完整错误处理流程

def handle_api_error(response):
    error = response.json().get('error', {})
    code = error.get('code')
    reason = error.get('errors', [{}])[0].get('reason')

    if code == 403:
        if reason == 'quotaExceeded':
            # 配额耗尽,停止当天任务
            raise QuotaExceededError("Daily quota exhausted")
        elif reason == 'accessNotConfigured':
            # API 未启用
            raise ConfigurationError("YouTube API not enabled")
    elif code == 429:
        # 速率限制,需要重试
        raise RateLimitError("Too many requests")
    elif code == 404:
        # 资源不存在,可忽略
        return None
    elif code == 400:
        # 参数错误,记录并修复
        raise BadRequestError(f"Invalid parameters: {error}")

6. 响应数据结构

6.1 标准响应格式

{
  "kind": "youtube#videoListResponse",
  "etag": "\"some-etag\"",
  "items": [
    {
      "kind": "youtube#video",
      "etag": "\"item-etag\"",
      "id": "dQw4w9WgXcQ",
      "snippet": {
        "publishedAt": "2009-10-25T06:57:33Z",
        "channelId": "UC_...",
        "title": "Video Title",
        "description": "Video description...",
        "thumbnails": {
          "default": {"url": "...", "width": 120, "height": 90},
          "medium": {"url": "...", "width": 320, "height": 180},
          "high": {"url": "...", "width": 480, "height": 360},
          "standard": {"url": "...", "width": 640, "height": 480},
          "maxres": {"url": "...", "width": 1280, "height": 720}
        },
        "channelTitle": "Channel Name",
        "tags": ["tag1", "tag2"],
        "categoryId": "10",
        "liveBroadcastContent": "none"
      },
      "contentDetails": {
        "duration": "PT3M33S",
        "dimension": "2d",
        "definition": "hd",
        "caption": "false",
        "licensedContent": true
      },
      "statistics": {
        "viewCount": "1234567890",
        "likeCount": "12345678",
        "favoriteCount": "0",
        "commentCount": "2345678"
      }
    }
  ],
  "pageInfo": {
    "totalResults": 200,
    "resultsPerPage": 50
  },
  "nextPageToken": "..."
}

6.2 字段说明

字段路径 类型 说明 注意事项
id string 视频唯一 ID 必需
snippet.title string 视频标题 必需
snippet.description string 视频描述 可能为空
snippet.channelId string 频道 ID 必需
snippet.channelTitle string 频道名称 必需
snippet.publishedAt ISO 8601 发布时间 UTC 时间
snippet.thumbnails.*.url string 缩略图 URL 多尺寸可选
snippet.tags array 标签列表 可能为空或缺失
snippet.categoryId string 分类 ID 必需
statistics.viewCount string 观看次数 字符串数字
statistics.likeCount string 点赞数 可能缺失
statistics.commentCount string 评论数 可能缺失
contentDetails.duration ISO 8601 视频时长 PT#M#S 格式

⚠️ likeCount 和 commentCount 可能因视频设置(关闭评论/隐藏点赞)而缺失,抽取时必须做默认值处理。


7. 数据导出格式

7.1 JSON 导出

{
  "crawl_time": "2026-04-01T12:00:00Z",
  "region": "US",
  "category": "10",
  "videos": [
    {
      "videoId": "dQw4w9WgXcQ",
      "url": "https://youtube.com/watch?v=dQw4w9WgXcQ",
      "title": "...",
      "channelTitle": "...",
      "viewCount": 1234567890,
      "likeCount": 12345678,
      "thumbnails": {...},
      "publishedAt": "2009-10-25T06:57:33Z",
      "duration": 213
    }
  ]
}

7.2 CSV 导出

videoId,title,channelTitle,viewCount,likeCount,url,publishedAt
"dQw4w9WgXcQ","Rick Astley - Never Gonna Give You Up","Rick Astley",1540000000,12500000,"https://youtube.com/watch?v=dQw4w9WgXcQ","2009-10-25T06:57:33Z"

8. 完整调用示例

8.1 获取单个地区热门视频

curl "https://www.googleapis.com/youtube/v3/videos?\
part=snippet,statistics,contentDetails&\
chart=mostPopular&\
regionCode=US&\
maxResults=50&\
key=YOUR_API_KEY"

8.2 获取特定分类热门视频

curl "https://www.googleapis.com/youtube/v3/videos?\
part=snippet,statistics&\
chart=mostPopular&\
regionCode=US&\
videoCategoryId=10&\
maxResults=50&\
key=YOUR_API_KEY"

8.3 Python 实现

import requests
import os

API_KEY = os.getenv('YOUTUBE_API_KEY')
BASE_URL = 'https://www.googleapis.com/youtube/v3/videos'

def get_trending_videos(region='US', category=None, max_results=50):
    params = {
        'part': 'snippet,statistics,contentDetails',
        'chart': 'mostPopular',
        'regionCode': region,
        'maxResults': max_results,
        'key': API_KEY
    }

    if category:
        params['videoCategoryId'] = category

    response = requests.get(BASE_URL, params=params)
    response.raise_for_status()

    return response.json()

# 获取美國 Music 分类热门视频
videos = get_trending_videos(region='US', category='10')

9. 备用方案: yt-dlp

当 API 配额耗尽或无法获取 Key 时使用。

import yt_dlp

def get_trending_ytdlp(limit=50):
    ydl_opts = {
        'extract_flat': True,
        'playlistend': limit,
        'quiet': True,
        'no_warnings': True,
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(
            'https://www.youtube.com/feed/trending',
            download=False
        )

        return [
            {
                'videoId': e.get('id'),
                'url': f"https://youtube.com/watch?v={e.get('id')}",
                'title': e.get('title'),
                'channelTitle': e.get('uploader'),
                'viewCount': e.get('view_count'),
                'thumbnail': e.get('thumbnail'),
            }
            for e in info.get('entries', [])
        ]

10. 参考资源