Chuyển đến nội dung
VI
Lấy khóa API
Duyệt tài liệu

Ví dụ

YouTube Search API: hướng dẫn Python

Tìm YouTube theo từ khóa, lọc video và xuất CSV, JSONL cùng ID video đã loại trùng bằng Python.

Trên trang này

Tìm kiếm YouTube bằng Python

Python SDK
python -m pip install -U flashdata
search.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"])

Phản hồi tìm kiếm thực tế

Đây là ba kết quả đầu trong 20 kết quả của bản demo công khai cho “battery recycling process” ngày 15 tháng 11 năm 2026. Bản ghi giữ sáu trường cho mỗi video. Chạy demo trực tiếp để lấy kết quả mới.

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
  }
]

Gộp nhiều lượt tìm kiếm thành tập dữ liệu

Bộ công cụ Python lưu phản hồi đã hoàn tất, loại ID video trùng và giữ lại từng truy vấn cùng vị trí kết quả phù hợp. Tiếp tục với cùng tùy chọn và resume=True để dùng lại các lượt tìm kiếm đã hoàn tất.

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

Tìm kiếm tiêu chuẩn hay mở rộng?

Tìm kiếm tiêu chuẩn chấp nhận 1–20 kết quả mỗi truy vấn. Tìm kiếm mở rộng chấp nhận 1–700 với mức phí riêng. Cả hai mặc định là 20; max_results là giới hạn, không phải số kết quả được bảo đảm.

Lọc theo thời lượng, ngày tải lên, thứ tự và phụ đề. Các endpoint này không cung cấp số trang hoặc token tiếp tục. Dùng tìm kiếm mở rộng để có thêm kết quả.

Lấy thêm kết quả bằng tìm kiếm mở rộng
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")

Thu hẹp việc tìm kiếm khi cần thiết

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",
        },
    )

Chọn những gì cần làm giàu tiếp theo

Dùng video-ids.txt làm đầu vào cho metadata, bản chép lời hoặc tải xuống hàng loạt. Xem xét video ứng viên trước khi chọn ID cần bổ sung dữ liệu hoặc phân phối.

Nhiệm vụ tiếp theo của bạnDùng IDs đã chọn cho
Kiểm tra chi tiết của videoLấy siêu dữ liệu cho điều đã chọn ID. Kiểm tra transcriptLanguages trước khi yêu cầu một đoạn ghi chú cụ thể.
tổng hợp nội dung đã nóiHãy đọc một bản sao hoặc phần phụ đề sẵn có và trích dẫn nhãn thời gian. Đừng chỉ tóm tắt đoạn băng trong phần tìm kiếm.
Làm giàu nhiều videoDùng selected-video-ids.txt để nhập vào hướng dẫn làm giàu. Siêu dữ liệu và chú thích là những yêu cầu riêng biệt với quyền hạn và cáo buộc của riêng họ.

Ví dụ REST đầy đủ có lưu phản hồi

Tùy chọn: dùng trực tiếp requests hoặc cURL. Lưu request.json cạnh tập lệnh. Nhập khóa API vào biến key trong Python; Bash đọc FLASHDATA_API_KEY hoặc yêu cầu nhập khóa. Mỗi thư mục đầu ra mới gửi một lượt tìm kiếm.

Chạy với tìm kiếm-001 là thư mục xuất. Một thư mục mới đệ trình một tìm kiếm có thể thanh toán được; một thư mục đã có được đọc ở địa phương. Tập lệnh giữ yêu cầu gửi đi, đáp ứng và sử dụng chính xác.

youtube-search/request.json
{
  "source": "youtube_search",
  "query": "battery recycling process explained",
  "params": {
    "max_results": 5,
    "filters": {
      "type": "video"
    }
  }
}
Cài đặt trong môi trường Python của bạn
python -m pip install requests
youtube-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")
Chạy từ bạn ống dò /
python search.py search-001

Nếu tìm kiếm cần sự chú ý

Chuyện gì đã xảy raCách xử lý
Ít hơn năm video, hoặc không cóĐây có thể là một cuộc tìm kiếm thành công. Chỉnh lại yêu cầu hoặc gỡ bỏ bộ lọc hạn chế. totalResults Mô tả phản ứng này, không phải tổng số khớp YouTube video.
401 / 403 / 402Kiểm tra chìa khóa đi. youtube_search cho phép và số dư, anh bạn. Sửa chữa nguyên nhân trước khi tạo ra một nỗ lực mới.
429Với HTTP 429, đợi theo Retry-After. Bộ công cụ chỉ thử lại phản hồi 429 rõ ràng, mặc định tối đa hai lần, và dừng nếu thời gian chờ vượt 60 giây. Ví dụ SDK trực tiếp và REST không tự thử lại.
Thời hạn, 5x hoặc một thư mục không đầy đủGiữ các tệp đã lưu và kiểm tra lịch sử trên console trước khi gửi lại. Bộ công cụ không tự gửi lại yêu cầu có kết quả chưa xác định.