跳转到正文
Social2api

文档 使用指南 操作指南

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

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

DataXAPI 价目生效日期与版本 2026-11-25 · v22

查看 YouTube 视频评论列表 API 的参数与示例

本页用到的 Social2api 接口

接口与参数文档用途
YouTube 视频评论列表GET /v1/youtube/videos/comments/listYouTube 视频评论列表。返回一页 data.items,以及可用的下一页游标。
YouTube 评论回复列表GET /v1/youtube/comments/replies/listYouTube 评论回复列表。返回一页 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。

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_idqueried_parent_idparent_id
youtube-comments.csvcomment-A——
youtube-replies.csvreply-Acomment-Acomment-A(如返回)

核对分页和调用费用

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

只在 page.has_more 为 true 且存在 page.next_cursor 时继续。下一页将该游标原样作为 cursor,继续使用相同查询和供应商。

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

接口DataXAPI 通道参考价与上限
YouTube 视频评论列表 API每页最多 20 条,每页 US$0.002
YouTube 评论回复列表 API每页最多 50 条,每页 US$0.002

接口文档

参考来源

相关用户讨论

查看 YouTube 视频评论列表 API 的参数与示例