# Thu thập siêu dữ liệu của một video

Quay một YouTube video ID vào danh hiệu, kênh, thời gian và số lượng có sẵn của nó. Giữ phản ứng và sử dụng bên cạnh nó.

Tài liệu tham khảo chính điển: https://flashdata.dev/vi/docs/guides/video-metadata-recipe
Xem lại: 2026-11-05 by FlashData

<a id="prepare"></a>

## Trước khi bắt đầu

Dùng phím youtube_metadata Cho phép và tín dụng sẵn có. Chọn Python 3.10+ với yêu cầu, hoặc Bash có cURL 7.76+ và jq. Vào Windowssử dụng Git Bash cho Bash phiên bản.

- [Lấy khóa API](https://flashdata.dev/app/api-keys)
- [Dùng thử tác nhân và liên kết tài khoản](https://flashdata.dev/vi/docs/guides/agent-onboarding/reference.md)
- [Tín dụng và giá cả](https://flashdata.dev/vi/docs/guides/credits-and-billing/reference.md)

<a id="input"></a>

## 1. Chọn một video

Tạo một thư mục đường thẳng video và lưu request.json ở đó. Mở một thiết bị cuối trong thư mục đó. Thay thế video_id với 11- Hồ sơ. ID từ một cái đồng hồ URL hoặc một YouTube Search kết quả; không vượt qua đầy đủ URL.

Đặt rõ cả hai cờ tùy chọn: Yêu cầu đầu tiên này bỏ qua định dạng phương tiện và chương. Nó thu thập siêu dữ liệu mà không cần tải video hoặc tiêu đề của nó.

### video-metadata/request.json

```json
{
  "source": "youtube_metadata",
  "video_id": "FUfGcZ092b0",
  "params": {
    "include_formats": false,
    "include_chapters": false
  }
}
```


<a id="run"></a>

## 2. Lấy và lưu siêu dữ liệu

Chọn một phiên bản và lưu văn lệnh bên cạnh request.json. Nó đọc FLASHDATA_API_KEY hoặc yêu cầu chìa khóa của bạn tại một dấu nhắc ẩn. Các tác nhân nên tải biến môi trường đó từ cửa hàng bí mật của họ.

Chạy với ảnh chụp...001 là thư mục xuất. Một thư mục mới gửi một yêu cầu siêu dữ liệu và lưu cách sử dụng đã báo cáo. Các tập lệnh kiểm tra một phản ứng thành công chứa chính xác một video với yêu cầu ID trước khi ghi video.json.

### Python

#### Cài đặt trong môi trường Python của bạn

```bash
python -m pip install requests
```

#### video-metadata/metadata.py

```python
import argparse
import getpass
import json
import os
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 snapshot")
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_metadata"
            or not isinstance(request.get("video_id"), str)
            or not re.fullmatch(r"[A-Za-z0-9_-]{11}", request["video_id"])):
        raise SystemExit("Use youtube_metadata and an 11-character video_id, not a URL")
    key = os.environ.get("FLASHDATA_API_KEY") or getpass.getpass("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")
try:
    data = json.loads((out / "result.json").read_bytes())
except ValueError:
    raise SystemExit("Invalid JSON; inspect the saved result.json")
request = json.loads((out / "request.json").read_bytes())
if not isinstance(data, dict) or data.get("source") != "youtube_metadata" or data.get("status") != "done":
    raise SystemExit("Metadata request did not finish successfully; inspect result.json")
videos = data.get("results")
if (not isinstance(videos, list) or len(videos) != 1 or not isinstance(videos[0], dict)
        or videos[0].get("videoId") != request["video_id"]):
    raise SystemExit("Expected one metadata object matching the requested video_id")
record = {
    "request": request,
    "requested_at": (out / "requested-at.txt").read_text().strip(),
    "usage": data.get("usage"), "result_file": "result.json",
}
for filename, value in (("video.json", videos[0]), ("record.json", record)):
    (out / filename).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Saved {videos[0]['videoId']} to {out}/video.json")
```

#### Chạy từ video-metadata /

```bash
python metadata.py snapshot-001
```


### Bash

#### Kiểm tra dụng cụ của bạn

```bash
curl --version
jq --version
```

#### video-metadata/metadata.sh

```bash
#!/usr/bin/env bash
set -euo pipefail
out="${1:?Usage: bash metadata.sh OUTPUT_FOLDER}"

if [[ ! -e "$out" ]]; then
  jq -e '.source == "youtube_metadata" and
    (.video_id | if type == "string" then length == 11 and test("^[A-Za-z0-9_-]{11}$")
     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
video=$(jq -e --slurpfile request "$out/request.json" '
  if .source != "youtube_metadata" or .status != "done"
  then error("Expected a successful youtube_metadata response") else . end
  | .results
  | if type != "array" then error("Expected a metadata array")
    elif length != 1 then error("Expected exactly one video") else .[0] end
  | if type != "object" then error("Expected a metadata object")
    elif .videoId != $request[0].video_id then error("Returned videoId does not match the request")
    else . end' "$out/result.json")
printf '%s\n' "$video" > "$out/video.json"
jq --slurpfile request "$out/request.json" \
  --arg requested_at "$(tr -d '\r\n' < "$out/requested-at.txt")" \
  '{request: $request[0], requested_at: $requested_at, usage, result_file: "result.json"}' \
  "$out/result.json" > "$out/record.json"
printf 'Saved %s to %s/video.json\n' "$(jq -r .videoId "$out/video.json")" "$out"
```

#### Chạy từ video-metadata /

```bash
bash metadata.sh snapshot-001
```



<a id="output"></a>

## 3. Đọc đĩa thu hình

Lưu bản in thành công <video ID> đến snapshot-001/video.json. Đọc tập tin đó cho đối tượng siêu dữ liệu đầy đủ và record.json cho yêu cầu được nộp, requested_at và sử dụng. Đọc những tập tin này không gọi cho API.

### Python

#### Đọc ở địa phương

```bash
python -m json.tool snapshot-001/video.json
python -m json.tool snapshot-001/record.json
```


### Bash

#### Đọc ở địa phương

```bash
cat snapshot-001/video.json
cat snapshot-001/record.json
```



<a id="expected"></a>

### Đầu ra Ví dụ

Được viết tắt, minh họa video.json. Các giá trị được trả lại khác nhau. Văn lệnh bảo tồn mọi lĩnh vực, bao gồm giá trị của null, và giữ câu trả lời đầy đủ trong result.json.

#### video-metadata/snapshot-001/video.json

```json
{
  "videoId": "FUfGcZ092b0",
  "title": "Example research video",
  "channel": "Example channel",
  "duration": 120,
  "viewCount": null,
  "transcriptLanguages": [
    "en"
  ]
}
```


<a id="fields"></a>

### Đọc các cánh đồng

| Tìm kiếm | Dùng nó đi |
| --- | --- |
| videoId | Kỷ lục ổn định. Tên và kênh hiển thị có thể thay đổi tên. |
| duration | Đoạn phim dài vài giây. Bảo tồn bị mất hoặc null giá trị như chưa biết. |
| viewCount / likeCount / commentCount | Các số liệu có trong hình ảnh này. Không biết là không biết; số không là một số báo cáo. |
| transcriptLanguages | Ứng cử ngôn ngữ để yêu cầu một tiêu đề riêng. Danh sách này không xác định được đường ray là tự động hay bằng tay. |


<a id="reuse"></a>

## Dùng lại ảnh chụp hay yêu cầu khác

Chạy cùng một lệnh để xây dựng lại video.json và record.json từ phản ứng được cứu rỗi. Không cần yêu cầu phím hay mạng. Sửa chữa cấp cao request.json không thay đổi dữ liệu được lưu trữ bằng ảnh chụp-001.

### Python

#### Dùng lại dữ liệu đã lưu

```bash
python metadata.py snapshot-001
```


### Bash

#### Dùng lại dữ liệu đã lưu

```bash
bash metadata.sh snapshot-001
```


- [Lưu và sử dụng lại kết quả](https://flashdata.dev/vi/docs/guides/save-results/reference.md)

<a id="chapters"></a>

### Gồm các chương sẵn sàng

Để bao gồm các đánh dấu chương, thay thế request.json với phiên bản này và dùng một thư mục xuất mới. include_chapters: true hoặc gửi các chương đến khi có sẵn, nhưng không tạo ra chúng. Cả hai include_chapters và include_formats mặc định true khi bị bỏ qua.

#### video-metadata/request.json

```json
{
  "source": "youtube_metadata",
  "video_id": "FUfGcZ092b0",
  "params": {
    "include_formats": false,
    "include_chapters": true
  }
}
```

#### Python

##### Yêu cầu chụp ảnh khác

```bash
python metadata.py snapshot-002
```


#### Bash

##### Yêu cầu chụp ảnh khác

```bash
bash metadata.sh snapshot-002
```


- [Trường siêu dữ liệu và tùy chọn](https://flashdata.dev/vi/docs/sources/youtube_metadata/reference.md)

<a id="recover"></a>

## Nếu không có siêu dữ liệu

| Chuyện gì đã xảy ra | Cách xử lý |
| --- | --- |
| video_id không hợp lệ | Chỉ sử dụng 11- Hồ sơ. ID. Việc nhập chứng nhận bị dừng trước khi gửi yêu cầu. |
| Riêng, bị gỡ bỏ hay bị hạn chế video | Cứ để thất bại như thế ID. Hãy kiểm tra lỗi nguồn, rồi chọn một video có thể truy cập, thay vì liên tục gửi cùng một mục. |
| Kết quả trống hoặc khác videoId | Văn lệnh dừng lại mà không cần ghi video.json. Kiểm tra yêu cầu lưu và đáp ứng trước khi dùng hồ sơ. |
| Thiếu số, chương hoặc ngôn ngữ | Một bản ghi siêu dữ liệu tương ứng vẫn có thể thành công. Bảo tồn các trường không sẵn sàng là không rõ; không điền vào chúng những giá trị đã phát minh. |
| 401 / 403 / 402 | Kiểm tra chìa khóa đi. youtube_metadata cho phép và số dư trước một nỗ lực mới. |
| 429 | Đọc Retry-After in response-headers.txt và chờ đợi. Văn lệnh không bao giờ tự động sao lưu. |
| Thời hạn, 5xx, không hợp lệ JSON hoặc thư mục không đầy đủ | Cứ tiếp tục cố gắng và kiểm tra History trước khi nộp lại. Việc sử dụng lại thư mục của nó không đưa ra yêu cầu mới. |

### Python

Lưu inspect_metadata.py bên cạnh metadata.pyVậy thì chạy đi.

#### video-metadata/inspect_metadata.py

```python
from pathlib import Path

for name in ("http-status.txt", "response-headers.txt", "result.json"):
    path = Path("snapshot-001") / name
    print(f"--- {name} ---")
    print(path.read_text(encoding="utf-8", errors="replace") if path.exists() else "Not saved")
```

#### Kiểm tra cục bộ

```bash
python inspect_metadata.py
```


### Bash

#### Kiểm tra cục bộ

```bash
for name in http-status.txt response-headers.txt result.json; do
  printf '\n--- %s ---\n' "$name"
  if [[ -f "snapshot-001/$name" ]]; then cat "snapshot-001/$name"; else printf 'Not saved\n'; fi
done
```


- [Yêu cầu lịch sử](https://flashdata.dev/app/jobs)
- [Lỗi và mã trạng thái](https://flashdata.dev/vi/docs/errors/reference.md)

<a id="next"></a>

## Dùng đoạn phim trong luồng làm việc của bạn

Sử dụng videoId để tham gia kỷ lục này vào kết quả tìm kiếm của bạn hoặc bộ dữ liệu. Để biết thêm chi tiết, xin hãy tìm một phụ đề cụ thể. Đối với một số IDs, hãy dùng hướng dẫn làm giàu. Đây là những yêu cầu khác nhau với sự cho phép và cáo buộc của riêng họ.

- [Lấy phụ đề thời gian](https://flashdata.dev/vi/docs/guides/timestamped-captions-recipe/reference.md)
- [Enrich đã chọn phim IDs](https://flashdata.dev/vi/docs/guides/enrich-youtube-videos/reference.md)
