浏览文档
指南
寻找相关视频、选择字幕轨道,并处理频道新视频,避免重复工作。
本页内容
从已知信息开始
每种来源解决不同问题。已有视频 ID 或频道句柄时跳过发现步骤,仅补全任务所需的视频。
| 你的任务 | 来源 | 选择 |
|---|---|---|
| 寻找某主题的视频 | youtube_search | 先获取五个候选,再按相关性选择。 |
| 检查已知视频 | youtube_metadata | 获取标题、频道、时长和字幕语言。 |
| 概括或引用视频口述内容 | youtube_transcript / youtube_captions | 选择语言及自动或人工轨道。 |
| 检查频道近期视频 | youtube_channel | 将返回 ID 与已处理 ID 对比。 |
运行请求示例
按显示的文件名保存各 JSON 请求。Python 使用下方 query.py;cURL 可提交同一文件。密钥需具有所需来源权限和可用 Credits。每次提交对应一次查询,与返回视频数量无关。
使用 Python 3.10+。安装 requests 并保存下方 query.py,再运行每个请求旁的命令。已有输出会复用;修改输入后使用新的输出文件名。
python -m pip install requests使用 Bash。将 REQUEST.json 和 RESULT.json 替换为所选示例的文件名。重复请求前检查结果;此命令也会保存错误的 HTTP 响应。
(
set -eu
: "${FLASHDATA_API_KEY:?Set FLASHDATA_API_KEY first}"
test ! -e RESULT.json || { echo 'Read RESULT.json first'; exit 1; }
curl --fail-with-body --silent --show-error --max-time 70 \
--request POST 'https://data.flashdata.dev/v1/queries/realtime' \
--header "X-API-Key: $FLASHDATA_API_KEY" \
--header 'Content-Type: application/json' \
--data-binary @REQUEST.json --output RESULT.json
)设置 API Key
复用终端或密钥存储中的 FLASHDATA_API_KEY。若尚未设置,选择下方一个隐藏提示输入密钥,在运行示例的进程中保留此变量。
# Bash: paste the key into a hidden prompt, not into this command.
read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
printf '\n'
export FLASHDATA_API_KEY# PowerShell 7: paste the key into a hidden prompt.
$flashdataSecureKey = Read-Host "FlashData API key" -AsSecureString
$env:FLASHDATA_API_KEY = [System.Net.NetworkCredential]::new("", $flashdataSecureKey).Password
Remove-Variable flashdataSecureKey为 Python 示例保存 query.py
在新工作目录创建 query.py,复制下方完整代码。将请求 JSON 文件及其他 Python 脚本保存到同一目录,并在该目录运行全部命令。
# query.py — submit a saved request once, then reuse its response.
import json
import os
import sys
from pathlib import Path
import requests
if len(sys.argv) != 3:
raise SystemExit("Usage: python query.py REQUEST.json RESULT.json")
payload = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8-sig"))
output = Path(sys.argv[2])
marker = output.with_name(output.name + ".request.json")
receipt = output.with_name(output.name + ".http.json")
if marker.exists():
if json.loads(marker.read_text()) != payload:
raise SystemExit("Changed request: choose a new output filename.")
if not output.exists() or not receipt.exists():
raise SystemExit("Outcome unknown: check History before resubmitting.")
saved = json.loads(receipt.read_text())
if saved["status"] != 200 or json.loads(output.read_text(encoding="utf-8")).get("status") != "done":
raise SystemExit(f"Saved request failed or incomplete; Retry-After: {saved['retry_after']}. Inspect {output}.")
print(f"Read the saved {output}; no new query submitted.")
raise SystemExit(0)
if output.exists():
raise SystemExit("Output already exists. Read it or choose a new filename.")
key = os.environ["FLASHDATA_API_KEY"]
with marker.open("x", encoding="utf-8") as file:
json.dump(payload, file)
response = requests.post("https://data.flashdata.dev/v1/queries/realtime",
headers={"X-API-Key": key}, json=payload,
timeout=70, allow_redirects=False)
output.write_text(response.text, encoding="utf-8")
receipt.write_text(json.dumps({"status": response.status_code,
"retry_after": response.headers.get("Retry-After")}), encoding="utf-8")
if response.status_code != 200:
raise SystemExit(f"HTTP {response.status_code}; Retry-After: {response.headers.get('Retry-After')}")
if response.json().get("status") != "done":
raise SystemExit(f"Inspect {output} and History before retrying.")
print(json.dumps({"saved": str(output), "usage": response.json().get("usage")}, indent=2))先发现候选,再获取详情
视频筛选排除其他结果类型;subtitles 将发现范围缩小到带字幕的视频,但不选择语言,也不保证存在所需轨道。保存为 discover-request.json。
{
"source": "youtube_search",
"query": "battery recycling process explained",
"params": {
"max_results": 5,
"filters": {
"type": "video",
"subtitles": true
}
}
}python query.py discover-request.json search.json按相关性选择,而非直接使用第一个 ID
将 candidates.py 保存在 query.py 和 search.json 旁,并在该目录运行。它保持搜索顺序,并按视频 ID 去重。检查标题、频道和时长,再将选定 ID 复制到下一请求。空列表表示搜索已完成但没有候选。
# candidates.py — read a saved response; no API calls.
import json
import re
from pathlib import Path
data = json.loads(Path("search.json").read_text(encoding="utf-8"))
if data.get("status") != "done":
raise SystemExit("Search did not complete; inspect search.json.")
candidates, seen = [], set()
for item in (data.get("results") or [{}])[0].get("results", []):
video_id = item.get("videoId", "")
if not re.fullmatch(r"[A-Za-z0-9_-]{11}", video_id) or video_id in seen:
continue
seen.add(video_id)
candidates.append({"videoId": video_id, "title": item.get("title"),
"channel": item.get("channel"), "duration": item.get("duration"),
"url": "https://www.youtube.com/watch?v=" + video_id})
Path("candidates.json").write_text(json.dumps(candidates, indent=2), encoding="utf-8")
print(json.dumps(candidates, indent=2))python candidates.py仅在候选不足时扩大搜索
标准搜索的 max_results 上限为 20。更广泛的采集可使用 youtube_search_extended,上限为 700,单独计价。下例请求 50 个候选;批量补全前先检查结果是否有用。
{
"source": "youtube_search_extended",
"query": "battery recycling process explained",
"params": {
"max_results": 50,
"filters": {
"type": "video"
}
}
}python query.py extended-request.json extended.json仅获取功能所需的元数据
将示例 video_id 替换为选定 ID。简单视频卡片或字幕语言检查可关闭格式和章节;需要大纲时启用 include_chapters,需要选择媒体格式时启用 include_formats。
{
"source": "youtube_metadata",
"video_id": "FUfGcZ092b0",
"params": {
"include_formats": false,
"include_chapters": false
}
}python query.py metadata-request.json metadata.json检查可用语言
选择字幕前读取 results[0].transcriptLanguages。格式、章节和语言是返回视频对象的字段;用量记录位于外层响应。
| 设置 | 用途 |
|---|---|
| language | transcriptLanguages 中的代码,如 en 或 zh-Hans。此列表不区分人工和自动轨道。 |
| auto: true | 已有的自动生成字幕轨道。 |
| auto: false | 已有的人工提供字幕轨道。两种轨道类型不会自动回退。 |
python -m json.tool metadata.json明确选择语言和轨道
使用与元数据请求相同的 video_id,明确设置 language 和 auto。youtube_transcript 默认 auto: true,youtube_captions 默认 auto: false。两者均获取已有字幕,不执行语音转写。
{
"source": "youtube_transcript",
"video_id": "FUfGcZ092b0",
"params": {
"language": "en",
"auto": true
}
}python query.py captions-request.json captions.json为证据保留时间戳
将 cite-segments.py 保存在 captions.json 旁,并在该目录运行。引用使用 results[0].segments,start 和 end 的单位为秒。文本应同时保留 languageCode 和 isAutoGenerated。fullText 便于阅读,但不能替代分段时间。轨道缺失时先记录缺口,再决定是否值得另行查询。
import json
from pathlib import Path
response = json.loads(Path("captions.json").read_text(encoding="utf-8"))
if response.get("status") != "done":
raise SystemExit("Inspect captions.json before continuing.")
track = (response.get("results") or [{}])[0]
if not track.get("segments"):
raise SystemExit("No caption evidence was returned.")
for segment in track["segments"][:3]:
url = f"https://www.youtube.com/watch?v={track['videoId']}&t={int(segment['start'])}s"
print(segment["text"], url)python cite-segments.py仅处理已知频道的新视频
使用频道句柄和有界的 video_limit(1–100)。results[0].videos 是返回的近期列表;videoCount 是频道元数据,不是本次返回条数。选择能覆盖所需新视频的上限和运行频率。
{
"source": "youtube_channel",
"handle": "@TED",
"params": {
"video_limit": 10
}
}python query.py channel-request.json channel.json保留待处理队列与完成检查点
将 channel-queue.py 保存在 query.py 和 channel.json 旁,并在该目录运行。不带参数运行会创建 new-ids.json,然后为其中 ID 处理并保存证据。仅在全部待处理 ID 成功后运行 --commit;失败时保持检查点不变。此示例为每个频道使用独立目录和单个工作进程。
# channel-queue.py — plan first; commit only after every queued video is processed.
import json
import re
import sys
from pathlib import Path
checkpoint = Path("processed-ids.json")
processed = set(json.loads(checkpoint.read_text()) if checkpoint.exists() else [])
queue = Path("new-ids.json")
if sys.argv[1:] == ["--commit"]:
processed.update(json.loads(queue.read_text()))
temporary = checkpoint.with_suffix(".tmp")
temporary.write_text(json.dumps(sorted(processed)), encoding="utf-8")
temporary.replace(checkpoint)
queue.unlink()
print("Checkpoint saved.")
elif sys.argv[1:]:
raise SystemExit("Usage: python channel-queue.py [--commit]")
else:
data = json.loads(Path("channel.json").read_text(encoding="utf-8"))
if data.get("status") != "done":
raise SystemExit("Channel query did not complete.")
ids = dict.fromkeys(video.get("videoId", "") for video in
(data.get("results") or [{}])[0].get("videos", []))
new = [value for value in ids if re.fullmatch(r"[A-Za-z0-9_-]{11}", value)
and value not in processed]
if queue.exists() and json.loads(queue.read_text()) != new:
raise SystemExit("Finish the existing queue before replacing it.")
queue.write_text(json.dumps(new, indent=2), encoding="utf-8")
print(json.dumps(new, indent=2))python channel-queue.py
# Process every ID in new-ids.json and save its result first.
python channel-queue.py --commit明确开始新一轮频道检查
查询辅助脚本会复用已保存响应。下一轮定时检查需使用新的输出文件名,检查成功结果后将其复制为 channel.json,再生成队列。跨次运行保留 processed-ids.json。近期列表并非频道完整导出,也不是事件流。
python query.py channel-request.json channel-next.jsonpython -c "from shutil import copyfile; copyfile('channel-next.json', 'channel.json')"用搜索建议改进查询
建议在 results[0] 中返回词组,而非视频记录。选择有用词组后再发起 youtube_search。按研究受众设置语言和地区。
{
"source": "youtube_suggestions",
"query": "battery recycling",
"params": {
"language": "en",
"region": "US"
}
}python query.py suggestions-request.json suggestions.json保存许可标签,不将其当作使用授权
youtube_trainability 返回视频许可标签。permitted: ["all"] 对应 Creative Commons;["none"] 也包含许可元数据缺失。保留视频 ID、来源响应和检索日期。此标签不授予下载、再利用或训练权限。
{
"source": "youtube_trainability",
"video_id": "FUfGcZ092b0"
}python query.py license-request.json license.json为应用与智能体限定工作量
| 规则 | 实现 |
|---|---|
| 先筛选再补全 | 主题任务可限定为一次搜索、一个选定视频的元数据和一个字幕轨道。在应用中执行调用预算,并分别检查各来源价格。 |
| 按实际输入复用 | 元数据:视频 ID + 选项。字幕:视频 ID + 语言 + 轨道。频道快照还需检索时间或运行 ID。 |
| 证据缺失时停止 | 不要重试空搜索结果或静默切换字幕轨道。返回缺口,由用户或工作流决定下一步。 |
| 保留用量和失败记录 | 保存成功响应的 usage。429 时遵守 Retry-After;提交结果不确定时,先检查历史再发起新的计费查询。 |