浏览文档
示例
使用 Python 按关键词搜索 YouTube、筛选视频,并导出去重后的 CSV、JSONL 和视频 ID 文件。
本页内容
使用 Python 搜索 YouTube
Python SDK
python -m pip install -U flashdatasearch.py
from flashdata import FlashData
with FlashData(api_key="your-flashdata-api-key") as client:
result = client.youtube.search(
"battery recycling process",
max_results=5,
filters={"type": "video"},
)
for video in result["results"][0]["results"]:
print(video["title"], video["videoId"])
真实搜索响应
以下是 2026 年 11 月 15 日通过公开演示搜索“battery recycling process”所得 20 条结果中的前 3 条。记录保留每个视频的 6 个字段。运行在线演示可获取最新结果。
results[0].results · 3 / 20
[
{
"videoId": "s2xrarUWVRQ",
"title": "What *Really* happens to used Electric Car Batteries? - (you might be surprised)",
"channel": "JerryRigEverything",
"duration": 424,
"viewCount": 5679251,
"uploadDate": null
},
{
"videoId": "RW0itbw_ALI",
"title": "Recycling Batteries",
"channel": "mbmmllc",
"duration": 193,
"viewCount": 91440,
"uploadDate": null
},
{
"videoId": "dyDoOcBMAHw",
"title": "Why It's So Hard To Recycle Electric-Car Batteries | World Wide Waste",
"channel": "Business Insider India",
"duration": 376,
"viewCount": 880172,
"uploadDate": null
}
]将多次搜索汇集成数据集
Python 工具包会保存已完成的响应、去除重复视频 ID,并保留每条结果对应的查询和排名。使用相同参数及 resume=True,可复用已完成的搜索。
Python toolkit
python -m pip install "https://github.com/flashdatadev/youtube-search-api/releases/download/v0.1.0/flashdata_youtube_search_api-0.1.0-py3-none-any.whl"search_to_dataset.py
from flashdata_search import SearchClient, collect
with SearchClient(api_key="your-flashdata-api-key") as client:
summary = collect(
client,
["battery recycling process", "lithium battery recycling plant"],
"output/batteries",
max_results=20,
filters={"duration": "4-20", "subtitles": True},
)
print(summary["unique_videos"], "unique videos")
# output/batteries: videos.csv, videos.jsonl, video-ids.txt, summary.json
选择标准搜索还是扩展搜索?
标准搜索每次查询接受 1–20 条结果;扩展搜索接受 1–700 条,采用独立费率。两者默认均为 20。max_results 是上限,并不保证返回对应数量。
使用时长、上传日期、排序和字幕筛选条件缩小范围。这些端点不提供页码或翻页令牌。需要更多结果时,请使用扩展搜索。
使用扩展搜索获取更多结果
from flashdata import FlashData
with FlashData(api_key="your-flashdata-api-key") as client:
result = client.youtube.search_extended(
"battery recycling process",
max_results=100,
filters={"type": "video", "duration": "4-20"},
)
print(len(result["results"][0]["results"]), "returned results")
按需缩小搜索范围
filters
from flashdata import FlashData
with FlashData(api_key="your-flashdata-api-key") as client:
result = client.youtube.search(
"battery recycling process",
max_results=20,
filters={
"type": "video",
"duration": "4-20",
"subtitles": True,
"sort_by": "view_count",
},
)
选择下一步需要补全的内容
将 video-ids.txt 用作元数据、转录或批量下载工作流的输入。先审查候选视频,再选择需要补充信息或交付的 ID。
| 下一项任务 | 如何使用选定 ID |
|---|---|
| 检查视频详情 | 为选定 ID 获取元数据。请求特定字幕轨道前检查 transcriptLanguages。 |
| 总结口述内容 | 读取可用转写或字幕轨道,并引用时间戳。不要仅凭搜索描述总结视频内容。 |
| 补全多个视频 | 将 selected-video-ids.txt 作为视频补全指南的输入。元数据和字幕属于独立请求,需要对应权限并单独计费。 |
保存响应的完整 REST 示例
可选:直接使用 requests 或 cURL。将 request.json 与脚本放在一起。在 Python 的 key 变量中填入 API 密钥;Bash 版本读取 FLASHDATA_API_KEY 或提示输入。每个新输出目录会提交一次搜索。
将 search-001 作为输出文件夹运行。新文件夹提交一次计费搜索;已有文件夹只在本地读取。脚本保留实际提交的请求、响应和用量。
youtube-search/request.json
{
"source": "youtube_search",
"query": "battery recycling process explained",
"params": {
"max_results": 5,
"filters": {
"type": "video"
}
}
}安装到 Python 环境
python -m pip install requestsyoutube-search/search.py
import argparse
import json
import re
from datetime import datetime, timezone
from pathlib import Path
import requests
parser = argparse.ArgumentParser()
parser.add_argument("folder", help="New output folder, or an existing saved search")
out = Path(parser.parse_args().folder)
if not out.exists():
body = Path("request.json").read_bytes()
request = json.loads(body)
if (not isinstance(request, dict) or request.get("source") != "youtube_search"
or not isinstance(request.get("query"), str) or not request["query"].strip()):
raise SystemExit("request.json must contain youtube_search and a nonempty query")
key = "your-flashdata-api-key"
if not key.strip():
raise SystemExit("An API key is required")
out.mkdir()
(out / "request.json").write_bytes(body)
(out / "requested-at.txt").write_text(
datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), encoding="utf-8"
)
try:
response = requests.post(
"https://data.flashdata.dev/v1/queries/realtime",
headers={"X-API-Key": key, "Content-Type": "application/json",
"Accept": "application/json"},
data=body, timeout=120, allow_redirects=False,
)
except requests.RequestException:
raise SystemExit(f"Request interrupted. Keep {out} and check History before retrying.")
(out / "result.json").write_bytes(response.content)
(out / "response-headers.txt").write_text(
"\n".join(f"{k}: {v}" for k, v in response.headers.items()), encoding="utf-8"
)
(out / "http-status.txt").write_text(str(response.status_code), encoding="utf-8")
else:
print(f"Reading saved response from {out}; no API call.")
if not (out / "http-status.txt").exists():
raise SystemExit("Incomplete attempt. Keep the folder and check History before retrying.")
status = (out / "http-status.txt").read_text().strip()
if status != "200":
raise SystemExit(f"HTTP {status}: inspect {out}/result.json and response-headers.txt")
data = json.loads((out / "result.json").read_bytes())
if not isinstance(data, dict) or data.get("source") != "youtube_search" or data.get("status") != "done":
raise SystemExit("Search did not finish successfully; inspect result.json")
pages = data.get("results")
if not isinstance(pages, list) or any(
not isinstance(page, dict) or not isinstance(page.get("results"), list) for page in pages
):
raise SystemExit("Expected results[].results arrays; inspect result.json")
videos, seen, skipped, duplicates = [], set(), 0, 0
for page in pages:
for row in page["results"]:
if not isinstance(row, dict):
raise SystemExit("Expected video result objects; inspect result.json")
video_id = row.get("videoId")
if not isinstance(video_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{11}", video_id):
skipped += 1
elif video_id in seen:
duplicates += 1
else:
seen.add(video_id)
videos.append({**row, "url": "https://www.youtube.com/watch?v=" + video_id})
record = {
"request": json.loads((out / "request.json").read_bytes()),
"requested_at": (out / "requested-at.txt").read_text().strip(),
"usage": data.get("usage"), "video_count": len(videos),
"skipped_items": skipped, "duplicates_removed": duplicates, "result_file": "result.json",
}
for filename, value in (("videos.json", videos), ("record.json", record)):
(out / filename).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
(out / "video-ids.txt").write_text("".join(v["videoId"] + "\n" for v in videos), encoding="utf-8")
print(f"Saved {len(videos)} videos to {out}/videos.json and video-ids.txt")
在 youtube-search/ 中运行
python search.py search-001检查工具
curl --version
jq --versionyoutube-search/search.sh
#!/usr/bin/env bash
set -euo pipefail
out="${1:?Usage: bash search.sh OUTPUT_FOLDER}"
if [[ ! -e "$out" ]]; then
jq -e '.source == "youtube_search" and
(.query | if type == "string" then test("\\S") else false end)' request.json > /dev/null
if [[ -z "${FLASHDATA_API_KEY:-}" ]]; then
read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
printf '\n'
fi
: "${FLASHDATA_API_KEY:?An API key is required}"
mkdir -- "$out"
cp request.json "$out/request.json"
date -u +'%Y-%m-%dT%H:%M:%SZ' > "$out/requested-at.txt"
curl --fail-with-body --silent --show-error --max-time 120 \
--request POST 'https://data.flashdata.dev/v1/queries/realtime' \
--header "X-API-Key: $FLASHDATA_API_KEY" \
--header 'Content-Type: application/json' --header 'Accept: application/json' \
--data-binary "@$out/request.json" \
--dump-header "$out/response-headers.txt" --output "$out/result.json" \
--write-out '%{http_code}' > "$out/http-status.txt" || {
printf 'Request failed. Keep %s and inspect its saved files before retrying.\n' "$out" >&2
exit 1
}
else
printf 'Reading saved response from %s; no API call.\n' "$out"
fi
if [[ ! -f "$out/http-status.txt" ]] || [[ "$(cat "$out/http-status.txt")" != 200 ]]; then
printf 'Incomplete or failed attempt. Inspect the saved files and History before retrying.\n' >&2
exit 1
fi
selection=$(jq -e '
if .source != "youtube_search" or .status != "done" or (.results | type) != "array"
then error("Expected a successful youtube_search response") else . end
| [.results[] | if (.results | type) != "array"
then error("Expected a video list") else .results[] end
| if type != "object" then error("Expected video result objects") else . end]
| reduce .[] as $row ({seen: {}, videos: [], skipped: 0, duplicates: 0};
if ($row.videoId | if type == "string" then length == 11 and test("^[A-Za-z0-9_-]{11}$") else false end) == false
then .skipped += 1
elif .seen[$row.videoId] then .duplicates += 1
else .seen[$row.videoId] = true
| .videos += [$row + {url: ("https://www.youtube.com/watch?v=" + $row.videoId)}] end)
| del(.seen)' "$out/result.json")
printf '%s' "$selection" | jq '.videos' > "$out/videos.json"
jq -r '.[].videoId' "$out/videos.json" > "$out/video-ids.txt"
jq --slurpfile request "$out/request.json" --argjson selection "$selection" \
--arg requested_at "$(tr -d '\r\n' < "$out/requested-at.txt")" \
'{request: $request[0], requested_at: $requested_at, usage,
video_count: ($selection.videos | length), skipped_items: $selection.skipped,
duplicates_removed: $selection.duplicates, result_file: "result.json"}' \
"$out/result.json" > "$out/record.json"
printf 'Saved %s videos to %s/videos.json and video-ids.txt\n' "$(jq length "$out/videos.json")" "$out"
在 youtube-search/ 中运行
bash search.sh search-001搜索需要处理时
| 遇到的情况 | 处理方法 |
|---|---|
| 少于五个视频或没有视频 | 这也可能是成功搜索。调整查询或移除限制过严的筛选。totalResults 描述本次响应,不代表 YouTube 上全部匹配视频数。 |
| 401 / 403 / 402 | 分别检查密钥、youtube_search 权限和余额。先修复原因,再创建新尝试。 |
| 429 | 遇到 HTTP 429 时,按 Retry-After 等待。工具包仅对明确的 429 响应重试,默认最多两次;要求等待超过 60 秒时会停止。直接使用 SDK 或 REST 示例不会自动重试。 |
| 超时、5xx 或文件夹内容不完整 | 保留已保存的文件,并在再次提交前查看控制台历史记录。工具包不会自动重发结果未知的请求。 |