跳到导航

Instagram活动帖发布后,怎样比较两次观察间增加了多少互动?

要看一条 Instagram 活动帖在两次查询之间互动变化了多少,用同一个详情动作(instagram.v2.fetch_post_info 或 instagram.v3.get_post_info)各保存一次响应。核对两份响应的短码和账号一致后,用 instagram_snapshot.py 把每份响应导出为 CSV,再用 compare_instagram.py 在本地计算变化。只有一份响应时,先留作下一次观察的基线。

例如新品 Reel 发布当天记录点赞、评论和播放,次日再查一次。给团队的表保留两次采集时间、原值、净变化和来源。

先确定要回答的问题

想知道什么怎么观察
这条作品后来增加多少互动同一 shortcode、同一详情动作,在两个明确时点比较
几条活动作品哪条表现值得研究保留各自发布时间,尽量在相近发布后年龄观察,再看内容
为什么互动变化结合活动时间、内容与其他证据提出解释;快照只显示计数变化

最终交付两份快照、原始响应和一份变化报告,列出每项计数的前值、后值、净变化、时间间隔和可用状态。缺少播放数的图片帖仍可比较点赞和评论。

怎样给助手布置任务?

保存这条活动Reel现在的互动数据,带作品短码、文案、账号和查询时间。下次取得同一作品的新观察后,比较点赞、评论、播放的净变化,附两次来源;缺失项单列,并说明比较的时间段。

instagram_snapshot.py 保存一条作品的快照,compare_instagram.py 比较已保存的两次记录。第二次取数由你自己安排,两个脚本都不会安装定时任务。每次详情请求按价格页的当前价格计费,本地比较不用再请求帖子详情。

1. 准备目标与预算

准备帖子链接和链接里的 shortcode,用于 data:instagram.v2.fetch_post_info。现在先保存第一次观察,之后仍用同一个详情动作取第二次记录,两次记录才可比。已有有效响应时,直接从第 3 步开始。

2. 获取并保存详情

mkdir instagram-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":"instagram.v2.fetch_post_info","params":{"code_or_url":"<post_url_or_shortcode>"}}' \
-D instagram-query-1/response.headers \
-o instagram-query-1/response.json

把 <post_url_or_shortcode> 换成你的帖子。HTTP 失败时保留错误输出,不继续导出;HTTP 成功后仍要检查 response.json 里的业务 status。保留原始 JSON 和 request_id,方便追溯。

3. 导出指定帖子的指标

把下面的脚本保存为 instagram_snapshot.py,用 Python 3 执行。输入是 /v1/social-data/call 的直接响应。脚本按 action 选择 v2 的 data.data 或 v3 的 data.items[],并要求恰好一个条目的 code 匹配,不默认取第一项。缺失值写空,数值 0 保留,以公式字符开头的文本会被转义;目标 CSV 必须还不存在。

import csv, hashlib, json, pathlib, re, sys
from decimal import Decimal, InvalidOperation
source, destination, expected_code = sys.argv[1:4]
source_path = pathlib.Path(source).resolve()
raw = source_path.read_bytes()
r = json.loads(raw)
if r.get("status") != "succeeded" or r.get("error") is not None:
raise ValueError("Call did not succeed")
if not isinstance(r.get("request_id"), str) or not r["request_id"].strip():
raise ValueError("Missing request ID; cannot preserve query evidence")
action = r.get("action")
if action == "instagram.v2.fetch_post_info":
candidates = [r["data"]["data"]]
elif action == "instagram.v3.get_post_info":
candidates = r["data"]["items"]
else:
raise ValueError("Unsupported detail action")
matches = [x for x in candidates if isinstance(x, dict) and x.get("code") == expected_code]
if len(matches) != 1:
raise ValueError("Expected exactly one matching shortcode")
p = matches[0]
identity = p.get("id")
if identity is not None and not ((isinstance(identity, str) and identity.strip()) or (type(identity) is int and 0 <= identity <= 9007199254740991)):
raise ValueError("Post ID must be an original nonempty string or safe integer")
metrics = p.get("metrics") if action == "instagram.v2.fetch_post_info" else p
if not isinstance(metrics, dict):
raise ValueError("Missing metric object")
def count(value):
if value is None:
return None
if type(value) is int and 0 <= value <= 9007199254740991:
return value
if isinstance(value, str) and re.fullmatch(r"[0-9]+", value):
return int(value)
raise ValueError("Use a safe nonnegative integer or original ASCII digit string; do not guess a rounded metric")
def scalar(value):
if value is None: return ""
text = str(value)
return "'" + text if text.lstrip().startswith(("=", "+", "-", "@")) else text
row = [p.get("id"), p["code"], (p.get("caption") or {}).get("text"),
(p.get("user") or {}).get("username"), p.get("taken_at"),
count(metrics.get("like_count")), count(metrics.get("comment_count")), count(metrics.get("play_count")),
p.get("product_type"), r.get("request_id"), action, str(source_path), hashlib.sha256(raw).hexdigest()]
with pathlib.Path(destination).open("x", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["id","code","caption","username","taken_at","likes","comments","plays",
"product_type","request_id","action","source_file","source_sha256"])
writer.writerow([scalar(x) for x in row])
print(json.dumps({"rows":1,"code":p["code"],"action":action}))

4. 运行并核对结果

python3 instagram_snapshot.py instagram-query-1/response.json instagram-snapshot-1.csv YOUR_SHORTCODE

核对 code、username 与原始链接一致,rows 应为 1。v2 的点赞、评论、播放取自 metrics 对象,v3 的计数在帖子条目顶层。caption 是帖子文案,不是字幕。taken_at 是发帖时间,不是采集时间;本次采集时间另记在采集清单里。导出失败时先看错误信息,不要把失败样本改成零互动行重新生成。

5. 采集第二次快照,不覆盖第一次

第二次采集使用新文件名,并记录采集时间。只有同一 code 的有效快照才能比较 likes、comments、plays;缺失字段不参与差值。plays 不是独立触达,差值也不是新增粉丝数。比较前保留两份原始响应,不覆盖旧快照。

详情输入 · 指标字段 · 相似账号

依据:网关 data:instagram.v2.fetch_post_info、data:instagram.v3.get_post_info 的输出合同和当前响应渲染。

6. 用两次快照回答“这条 Reel 后来增加了多少互动?”

compare_instagram.py 用两份已保存的 CSV 在本地比较,不再发请求。两份快照必须来自同一短码、同一详情 action;时间参数传实际 API 查询时间,不传文件修改时间。照片没有播放数时保持缺失;点赞基线为 0 时也不计算“无限增长率”。compare_instagram.py 只算净变化,计数下调保留负数;净变化不是新增粉丝、独立触达或某次投放的贡献。

把下面的脚本保存为 compare_instagram.py,运行 python3 compare_instagram.py instagram-snapshot-1.csv 2026-11-16T10:00:00Z instagram-snapshot-2.csv 2026-11-17T10:00:00Z instagram-change.json,把示例时间换成你的查询时间。instagram-change.json 包含两个来源、两个请求 ID、观察间隔,以及每项计数的前值、后值和净变化。目标不一致、时间顺序颠倒、数值非法或输出文件已存在时,脚本停止。要比较不同帖子,按相同的发布后时长分别采集,不能用当前总量直接给内容效果排名。

import csv
import re
import hashlib
import json
import sys
from datetime import datetime
from decimal import Decimal, InvalidOperation
from pathlib import Path
before_file, before_time, after_file, after_time, output = sys.argv[1:]
def load(filename):
with Path(filename).open(encoding="utf-8-sig", newline="") as handle:
reader = csv.DictReader(handle)
expected = {"id", "code", "caption", "username", "taken_at", "likes", "comments", "plays", "product_type", "request_id", "action", "source_file", "source_sha256"}
if not expected.issubset(set(reader.fieldnames or [])):
raise SystemExit("Use complete snapshot headers, including empty metric columns")
rows = list(reader)
if len(rows) != 1 or not rows[0].get("code"):
raise SystemExit("Expected exactly one snapshot row with a shortcode")
return rows[0]
def stamp(value):
result = datetime.fromisoformat(value.replace("Z", "+00:00"))
if result.utcoffset() is None:
raise SystemExit("Use an actual query time with timezone")
return result
def verify_source(row):
source = Path(row["source_file"])
if not source.is_absolute():
raise SystemExit("Re-export snapshots with an absolute raw-response path")
raw = source.read_bytes()
digest = hashlib.sha256(raw).hexdigest()
if digest != row["source_sha256"]:
raise SystemExit("Raw response changed; do not compare this snapshot")
response = json.loads(raw)
if response.get("status") != "succeeded" or response.get("error") is not None or response.get("action") != row["action"] or response.get("request_id") != row["request_id"]:
raise SystemExit("Raw response does not match snapshot request identity")
data = response.get("data")
if not isinstance(data, dict):
raise SystemExit("Missing raw detail data")
if row["action"] == "instagram.v2.fetch_post_info":
candidates = [data.get("data")]
elif row["action"] == "instagram.v3.get_post_info":
candidates = data.get("items")
else:
raise SystemExit("Unsupported detail action")
if not isinstance(candidates, list):
raise SystemExit("Missing raw post list")
matches = [p for p in candidates if isinstance(p, dict) and p.get("code") == row["code"]]
if len(matches) != 1:
raise SystemExit("Raw response must contain exactly one matching shortcode")
post = matches[0]
raw_id = post.get("id")
if raw_id is not None and not ((isinstance(raw_id, str) and raw_id.strip()) or (type(raw_id) is int and 0 <= raw_id <= 9007199254740991)):
raise SystemExit("Unsafe or malformed raw post ID")
identity = "" if raw_id is None else str(raw_id)
if identity.lstrip().startswith(("=", "+", "-", "@")):
identity = "'" + identity
if identity != row["id"]:
raise SystemExit("CSV post identity differs from raw response")
metrics = post.get("metrics") if row["action"] == "instagram.v2.fetch_post_info" else post
if not isinstance(metrics, dict):
raise SystemExit("Missing raw metric object")
for field, key in (("likes", "like_count"), ("comments", "comment_count"), ("plays", "play_count")):
value = metrics.get(key)
if value is None:
expected = ""
else:
if type(value) is int and 0 <= value <= 9007199254740991:
expected = str(value)
elif isinstance(value, str) and re.fullmatch(r"[0-9]+", value):
expected = str(int(value))
else:
raise SystemExit("Raw metric is not a safe integer or original ASCII digit string")
if row[field] != expected:
raise SystemExit("CSV metric differs from raw response; re-export instead of editing")
return digest
before, after = load(before_file), load(after_file)
source_hashes = [verify_source(before), verify_source(after)]
allowed = {"instagram.v2.fetch_post_info", "instagram.v3.get_post_info"}
if before.get("action") not in allowed or after.get("action") not in allowed:
raise SystemExit("Unsupported detail action")
if Path(before_file).resolve() == Path(after_file).resolve():
raise SystemExit("Use two independently saved snapshot files")
for row in (before, after):
if not row.get("request_id") or not row.get("source_file"):
raise SystemExit("Each snapshot needs its request ID and raw-response source")
if before["request_id"] == after["request_id"] or before["source_file"] == after["source_file"]:
raise SystemExit("The snapshots must represent distinct saved queries")
if before["code"] != after["code"]:
raise SystemExit("Cannot compare different posts")
if before.get("id") and after.get("id") and before["id"] != after["id"]:
raise SystemExit("Conflicting post identity")
if not before.get("action") or before["action"] != after.get("action"):
raise SystemExit("Use the same detail action for both observations")
elapsed = (stamp(after_time) - stamp(before_time)).total_seconds()
if elapsed <= 0:
raise SystemExit("Follow-up must be later than baseline")
result = {"code": before["code"], "action": before["action"], "before_file": before_file,
"after_file": after_file, "before_collected_at": before_time, "after_collected_at": after_time,
"before_request_id": before.get("request_id"), "after_request_id": after.get("request_id"),
"elapsed_seconds": elapsed, "source_sha256": source_hashes,
"raw_identity_and_metrics_verified": True, "query_times": "caller_recorded_not_server_attested", "metrics": {}}
for field in ("likes", "comments", "plays"):
values = []
for row in (before, after):
value = row.get(field, "")
if value == "":
values.append(None)
continue
try:
number = Decimal(value)
if not number.is_finite() or number < 0 or number != number.to_integral_value():
raise InvalidOperation
except InvalidOperation:
raise SystemExit(f"Invalid {field} counter")
values.append(int(number))
a, b = values
result["metrics"][field] = {"before": a, "after": b, "net_change": b - a if a is not None and b is not None else None}
result["scope"] = "two public observations; not reach, attribution or follower growth"
with Path(output).open("x", encoding="utf-8") as handle:
json.dump(result, handle, ensure_ascii=False, indent=2)

发送增量报告前,回查原响应

instagram_snapshot.py 在 CSV 里记录原始响应的绝对路径和 SHA-256。compare_instagram.py 重新读取两份原始文件,核对成功状态、action、request_id、shortcode、通用帖子 id 和三个计数。手改 CSV 数字、换入另一份响应或改动原文字节,都会让报告停止生成。没有哈希的 CSV 要用保存的 JSON 重新导出,重新导出不需要再次调用 API。原始文件保留在记录的路径;移动原始文件后重新导出。

哈希只能发现相对于 CSV 所记录值的变化,不是服务器签名,不能证明同时被改写的 CSV 与 JSON 是真实的。查询时间由调用者记录。caption 和 username 只作背景,compare_instagram.py 不核验这两个字段。通用 id 列也不是评论请求所需的数字 media_id;查评论时使用详情到评论交接。

交付客户时附上两份 JSON、对应的两份 CSV 和 instagram-change.json。结论写成:“在记录的观察间隔内,该帖报告的点赞数由 A 变为 B,净变化 B−A。”缺失指标继续标为不可得,负数说明为计数下调,不把差值写成触达、转化或投放带来的增长。两个本地脚本都不发送请求。

后续请求放进另一个目录,例如 instagram-query-2;目录已存在时,mkdir ... && curl ... 会停止,不覆盖前一次的证据。采集时记录带时区的真实查询时间,不能用之后的 CSV 导出时间代替。curl 失败留下的响应头和正文只用于排错,不是有效快照。

为什么看起来像数字的值也会阻止报告?

每个计数必须是安全整数范围内的非负 JSON 整数,或原始 ASCII 数字字符串。0 仍为零,缺失仍为不可用。小数或指数形式的字符串、浮点数、布尔值、取整后的展示标签以及超出安全范围的数值整数,都会让导出和比较停止;不能把这些值补成零,也不能悄悄去掉其中的标点。超过安全整数范围的原始数字字符串在 Python 中仍能精确保留;通用帖子 ID 同样不能从已舍入的数值重建。

计数校验失败时,保留文件,并记录“不可比较:来源数值不合法或存在精度风险”。不要同时改原始 JSON 和哈希来强行生成客户结论,也不要自动追加付费请求。要和旧快照比较,先用旧快照保存的原始响应重新导出。外层状态成功但 error 非空的响应,两个脚本都拒绝处理。