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

如何优化YouTube API调用,避免快速耗尽每日配额?

问题描述

我正在开发一个小型Python脚本,用于扫描我的Discogs收藏库(一个追踪黑胶唱片收藏的数据库),提取每张唱片的所有歌曲并整理为列表。随后使用YouTube Data API,根据歌曲名、艺术家和厂牌信息搜索对应视频并保存视频ID,以此创建包含收藏库所有歌曲的YouTube播放列表。但目前仅搜索约100首歌后就会耗尽每日配额,请问如何优化搜索逻辑,避免快速用完10000的配额?

相关代码片段:

query = ' - '.join([artist, title, catno])
            
request = youtube.search().list(q=query, part='snippet',  maxResults=1)
res = request.execute()
video_id = res['items'][0]['id']['videoId']

优化方案

1. 替换API端点降低单次调用配额消耗

YouTube Data API中,search.list每次调用会消耗100单位配额,这是你快速耗尽配额的核心原因。如果能通过Discogs数据获取歌曲的ISRC码,可以改用videos.list端点直接按ISRC查询,单次仅消耗1单位配额:

# 假设从Discogs获取到歌曲的isrc_code
request = youtube.videos.list(part='id', id=f'isrc:{isrc_code}')
res = request.execute()
if res['items']:
    video_id = res['items'][0]['id']

2. 缓存已搜索结果避免重复调用

用本地缓存(字典或JSON文件)存储已查询过的(艺术家, 歌曲名)组合对应的视频ID,后续遇到相同条目直接读取缓存,完全跳过API调用:

import json

# 初始化缓存
cache_file = 'youtube_video_cache.json'
try:
    with open(cache_file, 'r') as f:
        video_cache = json.load(f)
except FileNotFoundError:
    video_cache = {}

# 生成缓存键
cache_key = f"{artist.strip()}-{title.strip()}"
if cache_key in video_cache:
    video_id = video_cache[cache_key]
else:
    # 执行搜索逻辑
    query = f"{artist} {title}"  # 简化查询,去掉catno(厂牌编号对YouTube搜索无意义)
    request = youtube.search().list(q=query, part='snippet', maxResults=1)
    res = request.execute()
    video_id = res['items'][0]['id']['videoId'] if res['items'] else None
    # 写入缓存
    video_cache[cache_key] = video_id
    with open(cache_file, 'w') as f:
        json.dump(video_cache, f, indent=2)

3. 简化搜索关键词提升精准度

去掉查询中的catno(厂牌编号),这个信息在YouTube搜索中几乎不会帮助匹配到目标歌曲,反而可能引入歧义,导致搜索结果不准确甚至需要重复调用。用艺术家 + 歌曲名的极简组合即可满足大部分匹配需求。

4. 增加错误处理减少无效配额消耗

处理搜索无结果、API调用失败的场景,避免反复重试浪费配额:

try:
    res = request.execute()
    if res['items']:
        video_id = res['items'][0]['id']['videoId']
    else:
        video_id = None
        print(f"无匹配视频:{artist} - {title}")
except Exception as e:
    video_id = None
    print(f"API调用失败:{str(e)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:48:19