# 如何导出 YouTube 视频评论和对应的回复

[规范网址](https://social2api.com/guides/youtube-export-video-comments-and-replies/)

给 Social2api 一个公开 YouTube 视频 ID，先用 view=full 取评论列表。DataXAPI 的回复请求需要把父评论 ext.replies\_token 作为 id。评论表和回复表仍用父评论的原始 ID 关联。

DataXAPI 价目生效日期与版本 [2026-11-25 · v22](https://social2api.com/pricing-catalog.json)

## Agent 提示词

~~~~text
请用 Social2api 完成这个任务：如何导出 YouTube 视频评论和对应的回复。
先请我确认输入（一个公开视频的 ID 或完整链接，以及需要读取回复的评论）和愿意付费的请求数。使用此页列出的扩展 API 及参数。
只读取允许公开访问的数据，保留可复核的 ID、warnings 和缺失字段，按此格式交付：逐行交付 comment_id、video_id、text、published_at 和可用的 parent_id。链接不到直接父评论时，保留是在查询哪条评论的回复时获得的数据。。
如果 API 没有返回相应的公开数据，请保留缺失并解释覆盖范围。
https://social2api.com/guides/youtube-export-video-comments-and-replies/
~~~~

[查看 YouTube 视频评论列表 API 的参数与示例](https://social2api.com/docs/api/catalog-youtube-videos-comments-list/)

## 本页用到的 Social2api 接口

| 接口与参数文档 | 用途 |
| --- | --- |
| [YouTube 视频评论列表](https://social2api.com/docs/api/catalog-youtube-videos-comments-list/) · GET /v1/youtube/videos/comments/list | YouTube 视频评论列表。返回一页 data.items，以及可用的下一页游标。 |
| [YouTube 评论回复列表](https://social2api.com/docs/api/catalog-youtube-comments-replies-list/) · GET /v1/youtube/comments/replies/list | YouTube 评论回复列表。返回一页 data.items，以及可用的下一页游标。 |

## 准备输入并完成取数

1. 先用视频 ID 查询评论，开启 view=full 读取上游字段，并选择固定排序。保持原查询与游标配对。
2. 保留父评论的 normalized id。只对含 ext.replies\_token 的评论请求回复，将该 token 传给 replies/list 的 id。每条父评论各有一条回复分页链。
3. 把两个结果写到各自 CSV，以 queried\_parent\_id 追溯被查询的父评论，同时保留上游实际返回的 parent\_id。

## 复制 Social2api 请求

在运行环境设置有 catalog 权限的 SOCIAL2API\_API\_KEY 和自己的 DATAXAPI\_API\_KEY。下方请求走 DataXAPI 通道，用公开示例输入展示可运行的请求，执行时会产生供应商请求。替换为自己的公开目标即可。

需要 Python 3。最多取两页顶层评论，再选第一条含 ext.replies\_token 的父评论取最多三页回复。未找到 token 时把原因写入 youtube-requests.json。

~~~~bash
set -eu
: "${SOCIAL2API_API_KEY:?Set a Social2api catalog key}" "${DATAXAPI_API_KEY:?Set a DataXAPI key}"

python3 - 'dQw4w9WgXcQ' <<'PY'
import json, os
from datetime import datetime, timezone
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen

def get(path, parameters, cap):
    headers = {
        "Authorization": "Bearer " + os.environ["SOCIAL2API_API_KEY"],
        "X-DataXAPI-Key": os.environ["DATAXAPI_API_KEY"],
        "X-Max-Price": cap,
    }
    request = Request("https://social2api.com" + path + "?" + urlencode(parameters), headers=headers)
    result = {"fetched_at": datetime.now(timezone.utc).isoformat()}
    try:
        with urlopen(request, timeout=30) as stream:
            response = json.load(stream)
    except HTTPError as error:
        return {}, {**result, "status": "http_error", "http_status": error.code}
    except (URLError, TimeoutError, ValueError):
        return {}, {**result, "status": "request_or_parse_error"}
    if not isinstance(response, dict):
        return {}, {**result, "status": "invalid_response"}
    result.update({
        "code": response.get("code"),
        "status": response.get("meta", {}).get("result_status", response.get("code")),
        "request_id": response.get("request_id"),
        "warnings": response.get("warnings", []),
    })
    return (response if response.get("code") == "ok" else {}), result

def save_json(filename, value):
    Path(filename).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
PREFIX = "youtube"
SOURCE_PREFIX = "https://www.youtube.com/watch?v="
TOP = "/v1/youtube/videos/comments/list"
REPLIES = "/v1/youtube/comments/replies/list"
TOP_CAP = "0.002"
REPLIES_CAP = "0.002"
MAX_REPLY_PAGES = 3
TOKEN_REQUIRED = True
TOP_QUERY = {"sort":"latest","view":"full"}

import csv
import sys

def pages(path, parameters, cap, max_pages, stage):
    cursors = set()
    rows = {}
    attempts = []
    for number in range(1, max_pages + 1):
        response, result = get(path, parameters, cap)
        attempt = {"stage": stage, "page": number, **result}
        attempts.append(attempt)
        items = response.get("data", {}).get("items")
        if not isinstance(items, list):
            attempt["stop_reason"] = "request failed or missing items"
            break
        rows.update({row["id"]: row for row in items if row.get("id")})
        page = response.get("page", {})
        cursor = page.get("next_cursor")
        if not page.get("has_more") or not cursor:
            attempt["stop_reason"] = "no next cursor returned"
            break
        if cursor in cursors:
            attempt["stop_reason"] = "repeated cursor"
            break
        cursors.add(cursor)
        parameters = {**parameters, "cursor": cursor}
    else:
        attempts[-1]["stop_reason"] = "page budget reached"
    return list(rows.values()), attempts

def spreadsheet_cell(value):
    if isinstance(value, str) and value.lstrip().startswith(("=", "+", "-", "@")):
        return "'" + value
    return value

def write_csv(filename, rows):
    with open(filename, "w", encoding="utf-8-sig", newline="") as output:
        writer = csv.writer(output)
        writer.writerow(["video_id", "comment_id", "queried_parent_id", "parent_id", "text", "published_at", "source_url"])
        writer.writerows([spreadsheet_cell(value) for value in row] for row in rows)

video_id = sys.argv[1]
video_url = SOURCE_PREFIX + video_id
query = {"id": video_id, **TOP_QUERY}
comments, attempts = pages(TOP, query, TOP_CAP, 2, "comments")
parent = next((row for row in comments if (row.get("ext") or {}).get("replies_token")), None) if TOKEN_REQUIRED else next(iter(comments), None)
replies = []
reply_reason = None
if parent:
    selector = {"id": parent["ext"]["replies_token"]} if TOKEN_REQUIRED else {"id": parent["id"], "post_id": video_id}
    replies, reply_attempts = pages(REPLIES, selector, REPLIES_CAP, MAX_REPLY_PAGES, "replies")
    attempts.extend(reply_attempts)
else:
    reply_reason = "no replies_token in the fetched comments" if TOKEN_REQUIRED else "no parent comment returned"
save_json(PREFIX + "-requests.json", {
    "video_id": video_id,
    "source_url": video_url,
    "queried_parent_id": parent["id"] if parent else None,
    "skipped_replies": reply_reason,
    "attempts": attempts,
})
def row_fields(row, queried_parent_id=None):
    return (video_id, row["id"], queried_parent_id, row.get("parent_id"),
            row.get("text"), row.get("published_at"), video_url)
if not comments and not any(attempt.get("code") == "ok" for attempt in attempts):
    raise SystemExit("No comments collected; see the requests log.")
write_csv(PREFIX + "-comments.csv", [row_fields(row) for row in comments])
write_csv(PREFIX + "-replies.csv", [row_fields(row, parent["id"]) for row in replies])
print(len(comments), "comments;", len(replies), "replies;", len(attempts), "requests")
PY
~~~~

## 核对结果与覆盖

逐行交付 comment\_id、video\_id、text、published\_at 和可用的 parent\_id。链接不到直接父评论时，保留是在查询哪条评论的回复时获得的数据。

关闭评论、内容不可见或查询覆盖不足时，结果可能为空或不完整。用 warnings 和实际返回行数标记覆盖，回复缺失时保留原评论。

## 输出样例（合成数据）

| 文件 | comment\_id | queried\_parent\_id | parent\_id |
| --- | --- | --- | --- |
| youtube-comments.csv | comment-A | — | — |
| youtube-replies.csv | reply-A | comment-A | comment-A（如返回） |

## 核对分页和调用费用

为两页视频评论和三页回复发出五次请求，DataXAPI 参考费用为 US$0.010。先指定回复采集范围可以控制成本。

只在 page.has\_more 为 true 且存在 page.next\_cursor 时继续。下一页将该游标原样作为 cursor，继续使用相同查询和供应商。

上游费用从自己的 DataXAPI 账户结算，上游尝试会计入 Social2api 调用用量。展示价格以本站价格清单为准。

| 接口 | DataXAPI 通道参考价与上限 |
| --- | --- |
| [YouTube 视频评论列表 API](https://social2api.com/docs/api/catalog-youtube-videos-comments-list/) | 每页最多 20 条，每页 US$0.002 |
| [YouTube 评论回复列表 API](https://social2api.com/docs/api/catalog-youtube-comments-replies-list/) | 每页最多 50 条，每页 US$0.002 |

## 接口文档

- [YouTube 视频评论列表 API](https://social2api.com/docs/api/catalog-youtube-videos-comments-list/)
- [YouTube 评论回复列表 API](https://social2api.com/docs/api/catalog-youtube-comments-replies-list/)

## 参考来源

- [Social2api 扩展接口计费清单](https://social2api.com/pricing-catalog.json)

## 相关用户讨论

- [研究者获取公开视频评论及对应回复的需求](https://www.reddit.com/r/webscraping/comments/1mvov92/)
- [批量整理 YouTube 评论的需求](https://www.reddit.com/r/learnpython/comments/gydq94/)

## 相关指南和问答

- [社媒评论 API](https://social2api.com/roles/posts-comments-list/)

[查看 YouTube 视频评论列表 API 的参数与示例](https://social2api.com/docs/api/catalog-youtube-videos-comments-list/)
