문서 둘러보기
예제
Python으로 YouTube를 키워드 검색하고 동영상을 필터링하여 중복을 제거한 CSV, JSONL, 동영상 ID 파일을 내보냅니다.
이 페이지의 내용
Python으로 YouTube 검색
python -m pip install -U flashdatafrom 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개 필드가 포함됩니다. 최신 결과는 실시간 데모에서 확인하세요.
[
{
"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 -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"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")
필요한 경우 검색 화살표
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를 선택하세요.
| 다음 작업 | 선택된 IDs를 사용하여 |
|---|---|
| 동영상 보기 | 선택한 ID에 대한 Fetch 메타데이터. 특정 캡션 트랙을 요청하기 전에 transcriptLanguages를 검사합니다. |
| 자주 묻는 질문 | 사용 가능한 성적표 또는 캡션 트랙 및 cite 타임스탬프를 읽으십시오. 그 검색 설명에서 비디오를 요약하지 마십시오. |
| Enrich 여러 동영상 | selected-video-ids.txt를 사용하여 엔리치먼트 가이드에 입력합니다. Metadata 및 captions는 자신의 허가 및 요금으로 별도의 요청입니다. |
응답을 저장하는 전체 REST 예제
선택 사항으로 requests 또는 cURL을 직접 사용할 수 있습니다. request.json을 스크립트 옆에 저장하고 Python의 key 변수에 API 키를 입력하세요. Bash는 FLASHDATA_API_KEY를 읽거나 입력을 요청합니다. 새 출력 폴더마다 검색이 한 번 제출됩니다.
출력 폴더로 검색-001로 실행합니다. 새 폴더는 청구 가능한 검색을 제출합니다. 기존 폴더는 로컬로 읽습니다. 스크립트는 정확한 제출된 요청, 응답 및 사용량을 유지합니다.
{
"source": "youtube_search",
"query": "battery recycling process explained",
"params": {
"max_results": 5,
"filters": {
"type": "video"
}
}
}python -m pip install requestsimport 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")
python search.py search-001curl --version
jq --version#!/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"
bash search.sh search-001검색이 주의해야 하는 경우
| 어떤 일이 있었는지 | 해결 방법 |
|---|---|
| 다섯 개 이상의 비디오, 또는 none | 이것은 성공적인 검색이 될 수 있습니다. 쿼리를 정의하거나 제한 필터를 제거하십시오. totalResults는 YouTube 비디오를 일치하는 총 수가 아닌이 응답을 설명합니다. |
| 401 / 403 / 402 | 키, youtube_search 권한 및 균형 확인, 각각. 새로운 시도를 만들기 전에 원인을 수정합니다. |
| 429 | HTTP 429에서는 Retry-After만큼 기다리세요. 도구는 명시적인 429만 기본 최대 두 번 재시도하며, 대기 시간이 60초를 넘으면 중단합니다. 직접 SDK 및 REST 예제는 자동 재시도하지 않습니다. |
| Timeout, 5xx 또는 불완전 폴더 | 저장된 파일을 보관하고 다시 제출하기 전에 콘솔 기록을 확인하세요. 도구는 결과가 불명확한 요청을 자동으로 다시 제출하지 않습니다. |