跳到导航

抖音分享链接的文案和互动数据怎么保存为 CSV?

要把抖音分享链接的详情和互动存成 CSV,先用 douyin.app.v3.fetch_one_video_by_share_url 取详情,再用 douyin_snapshot.py 从已保存的响应导出一行 CSV。表里保留作品 ID、文案、互动原值和采集时间。完播率要用你有权访问的同一作品的结案或后台报表核对。

1. 确定目标和费用

从一条真实分享链接开始,用免费的 /v1/capabilities/inspect 查询 data:douyin.app.v3.fetch_one_video_by_share_url 的当前价格。本任务只查一次详情并在本地导出,不读取评论,不下载素材。

2. 保存原始响应

mkdir douyin-query-1 &&
curl --fail-with-body -sS https://api.beatapi.io/v1/social-data/call \
-H "Authorization: Bearer $BEATAPI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"action":"douyin.app.v3.fetch_one_video_by_share_url","params":{"share_url":"<share_url>"}}' \
-D douyin-query-1/headers.txt \
-o douyin-query-1/detail.json

替换占位链接。HTTP 请求失败时停止并保留错误;保存原始 JSON,解析前检查业务 status。

3. 按实际字段导出

把下面的脚本保存为 douyin_snapshot.py。脚本拒绝失败或被过滤的结果,缺失和数值零分开保存,转义以公式符号开头的文本,并且只创建新文件。

import csv,hashlib,json,pathlib,sys
source,target=map(pathlib.Path,sys.argv[1:3])
source_bytes=source.read_bytes();digest=hashlib.sha256(source_bytes).hexdigest()
r=json.loads(source_bytes)
if not isinstance(r,dict) or r.get("error") is not None or r.get("status")!="succeeded" or r.get("action")!="douyin.app.v3.fetch_one_video_by_share_url":
raise ValueError("Expected successful share-link detail")
p=r.get("data",{}).get("aweme_detail")
if not isinstance(p,dict) or not p.get("aweme_id"):
raise ValueError("No usable aweme_detail; inspect filter_list and request_id")
if not isinstance(r.get("request_id"),str) or not r["request_id"].strip():
raise ValueError("Missing request_id")
if not isinstance(p["aweme_id"],str) or not p["aweme_id"].isascii() or not p["aweme_id"].isdigit() or not any(c!="0" for c in p["aweme_id"]):
raise ValueError("aweme_id must be a digit string")
for field in ("desc","share_url"):
if p.get(field) is not None and not isinstance(p[field],str):raise ValueError("Invalid text field: "+field)
if p.get("create_time") is not None and (type(p["create_time"]) is not int or not 0<=p["create_time"]<=9007199254740991):raise ValueError("Invalid publication timestamp")
stats=p.get("statistics")
if stats is None: stats={}
if not isinstance(stats,dict): raise ValueError("Invalid statistics")
for key in ["digg_count","comment_count","share_count","collect_count","play_count"]:
value=stats.get(key)
if value is not None and (type(value) is not int or not 0<=value<=9007199254740991):
raise ValueError("Invalid counter: "+key)
def cell(v):
if v is None:return ""
s=str(v)
return "'"+s if s.lstrip().startswith(("=","+","-","@")) else s
row=[p["aweme_id"],p.get("desc"),p.get("create_time"),p.get("share_url"),
stats.get("digg_count"),stats.get("comment_count"),stats.get("share_count"),
stats.get("collect_count"),stats.get("play_count"),r.get("request_id"),str(source.resolve()),digest]
with target.open("x",encoding="utf-8",newline="") as f:
w=csv.writer(f)
w.writerow(["aweme_id","caption","published_at","share_url","likes","comments","shares","collects","plays","request_id","source_file","source_sha256"])
w.writerow([cell(v) for v in row])
print(p["aweme_id"])

4. 运行并核对

python3 douyin_snapshot.py douyin-query-1/detail.json douyin-snapshot-1.csv

核对输出的 aweme_id 与目标作品一致。互动指标来自 statistics:digg_count、comment_count、share_count、collect_count、play_count。desc 是文案,不是字幕;create_time 是发布时间,采集时间另行记录。

5. 保留有意义的历史快照

下一次采集用新文件名,只比较同一 aweme_id 且两次都存在的指标。播放量不等于独立观众,comment_count 也不证明所有评论都能取到。保留 request_id 和原始响应;被过滤的结果不写成全零,不覆盖旧快照。

作品 ID · 视频地址

依据:后端九个历史输出样本和当前清洗渲染实现;两个脚本均已离线验证。

6. 从已保存作品生成合作交付核对表

核对约定的博主作品交付时,只看互动数字不能证明是约定的创作者,也不能证明文案包含要求的信息。复用已保存的详情生成核对表,不要重新购买每条作品。建立 delivery-manifest.json,填入预期视频 ID 和已确认的创作者数字 uid,不填昵称或 sec_uid。collected_at 是原始采集时间,不是导表的时间。

预期 ID 取自约定的交付名单或独立核对过的博主资料,不要把本次响应里的作者 uid 抄成预期值来“通过”检查。替换全部占位符和示例时间,填你自己的原始记录。

[
{
"file": "douyin-query-1/detail.json",
"expected_aweme_id": "<verified_video_id>",
"expected_author_uid": "<verified_author_uid>",
"required_caption_phrase": "<agreed_caption_phrase>",
"collected_at": "2026-11-16T10:00:00+08:00"
}
]

把下面的代码保存为 review_delivery.py。脚本只读取本地响应,视频 ID 不匹配或详情被过滤时停止,缺失指标留空。作者不匹配和文案缺失会明确列出,脚本不会自动判定交付通过。

import csv
import hashlib
import json
import sys
from datetime import datetime
from pathlib import Path
manifest, target = map(Path, sys.argv[1:3])
entries = json.loads(manifest.read_text(encoding="utf-8"))
if not isinstance(entries, list) or not entries:
raise SystemExit("Manifest must contain reviewed video records.")
rows, seen, requests = [], set(), set()
for entry in entries:
expected = entry.get("expected_aweme_id")
expected_author = entry.get("expected_author_uid")
phrase = entry.get("required_caption_phrase")
if not isinstance(expected, str) or not expected.isascii() or not expected.isdigit() or not any(c != "0" for c in expected) or expected in seen:
raise SystemExit("Each expected_aweme_id must be a unique digit string.")
if not isinstance(expected_author, str) or not expected_author.isascii() or not expected_author.isdigit() or not any(c != "0" for c in expected_author):
raise SystemExit("expected_author_uid must be a verified digit string, not nickname/sec_uid.")
if not isinstance(phrase, str) or not phrase.strip():
raise SystemExit("Set the exact caption phrase you want to check.")
collected = entry.get("collected_at")
if not isinstance(collected, str):
raise SystemExit("Record actual collected_at with timezone.")
moment = datetime.fromisoformat(collected.replace("Z", "+00:00"))
if moment.tzinfo is None:
raise SystemExit("collected_at requires timezone.")
source = manifest.parent / entry["file"]
source_bytes = source.read_bytes(); digest = hashlib.sha256(source_bytes).hexdigest()
raw = json.loads(source_bytes)
if not isinstance(raw, dict) or raw.get("error") is not None or raw.get("status") != "succeeded" or raw.get("action") != "douyin.app.v3.fetch_one_video_by_share_url":
raise SystemExit("Expected successful Douyin share-link detail.")
request_id = raw.get("request_id")
if not isinstance(request_id, str) or not request_id.strip() or request_id in requests:
raise SystemExit("Each observation needs a distinct request_id.")
post = raw.get("data", {}).get("aweme_detail")
if not isinstance(post, dict) or post.get("aweme_id") != expected:
raise SystemExit("Missing/filtered detail or aweme_id differs from the manifest.")
author = post.get("author")
if author is not None and not isinstance(author, dict):
raise SystemExit("Invalid author object.")
uid = (author or {}).get("uid")
if uid is not None and (not isinstance(uid, str) or not uid.isascii() or not uid.isdigit() or not any(c != "0" for c in uid)):
raise SystemExit("Invalid returned author uid.")
caption = post.get("desc")
if caption is not None and not isinstance(caption, str):
raise SystemExit("Invalid caption.")
if caption is not None and caption.strip() in {"[redacted]", "[redacted-depth]"}:
caption = None
author_check = "missing" if uid is None else ("match" if uid == expected_author else "mismatch")
phrase_check = "missing" if caption is None else ("present" if phrase in caption else "absent")
stats = post.get("statistics")
if stats is not None and not isinstance(stats, dict):
raise SystemExit("Invalid statistics.")
counts = []
for key in ["digg_count", "comment_count", "share_count", "collect_count", "play_count"]:
value = (stats or {}).get(key)
if value is not None and (type(value) is not int or not 0 <= value <= 9007199254740991):
raise SystemExit(f"Invalid counter: {key}")
counts.append(None if value is None else int(value))
rows.append([expected, expected_author, uid, author_check, phrase, phrase_check, caption,
*counts, collected, entry["file"], request_id, digest, "", ""])
seen.add(expected)
requests.add(request_id)
def cell(value):
if value is None:
return ""
value = str(value)
return "'" + value if value.lstrip().startswith(("=", "+", "-", "@")) else value
with target.open("x", encoding="utf-8", newline="") as output:
writer = csv.writer(output)
writer.writerow(["aweme_id", "expected_author_uid", "actual_author_uid", "author_check", "required_caption_phrase", "phrase_check", "caption", "likes", "comments", "shares", "collects", "plays", "collected_at", "source_file", "request_id", "source_sha256", "review_decision", "review_reason"])
writer.writerows([[cell(value) for value in row] for row in rows])
print(f"Wrote {len(rows)} delivery-review rows; no API calls made.")
python3 review_delivery.py delivery-manifest.json delivery-review.csv

打开 CSV 时把 ID 列按文本导入。先看 author_check 和 phrase_check,再填写 review_decision、review_reason。文案出现指定文字,不代表视频里实际展示一致;品牌说法、合作披露和产品展示仍要观看视频核对。核对表是运营核对,不是合规认证。互动数是观察时的总量,不是活动归因转化或去重触达。作品不可用是待解决事项,不是零表现交付。

两种导出都附原响应字节的 source_sha256,原响应文件和 CSV、清单一起保存。哈希只是本地文件标识,不是平台签名,也不证明采集时间。计数必须是安全的非负 JSON 整数;浮点、布尔或不安全的裸整数会让导出停止,不四舍五入成看似精确的结果。ID 必须是原始的非零 ASCII 数字字符串。已有采集目录会阻止再次请求,本地导出不会刷新作品。

复盘时,把播放和完播率分列

要比较教程留存,先固定作品和观察窗口。普通作品快照实际返回 statistics.play_count 时,记录为播放量。看星图视频报告时,把已确认的星图报告作品标识作为 item_id 传给 douyin.xingtu_v2.get_item_report_detail。当前没有登记固定的完播字段、比例单位和通用覆盖范围,所以只有实际报告给出口径和数据时,才记录原值、时间窗口和出处。

例如两条教程都能核对播放,只有一条有同口径完播率,就比较播放,把另一条的完播留空。之后取得两条报告时,再对齐时间和指标定义。发现完播较低时,接着检查开头是否交代用途、演示有没有过长空段,留下要验证的修改。