跳转到正文
Social2api

文档 使用指南 操作指南

怎样定时把上个完整自然周的抖音关键词趋势存成 CSV?

每周重复取数时,把计算日期窗口、调用查询和写归档分开验证。使用外部计划任务触发请求,每个归档文件附上实际覆盖区间与请求状态。

本页用到的 Social2api 接口

接口与参数文档用途
抖音关键词逐日趋势POST /api/run · task=douyin查询最多 20 个关键词的日搜索指数和可用的综合指数。

在 Social2api 使用抖音关键词逐日趋势

  1. 用 Python 的 ZoneInfo("Asia/Shanghai") 计算当天日期,取本周一,再分别减 7 天和 1 天作为上周起止日。
  2. 计划任务调用 POST /api/run,固定词表和日期。先用 demo 检查调度环境与解析,实时请求在已配置密钥和额度后运行。
  3. 检查 HTTP 状态、warnings 和关键词覆盖。演示的合成数据提示为预期输出。实时结果先写临时文件,再写入含起止日的最终路径;有缺口时为这周单独留异常记录。

复制请求并试跑

用固定上周 2025 年 3 月 3 至 9 日验收导出日期列,周期性执行由外部计划任务负责。

这条请求使用合成样例,免登录、免 API Key,上游请求数为 0。要查真实数据,将 mode 改为 live,换成实际输入,并在 Authorization 中提供有相应任务权限的 Bearer API Key。可用 maxRequests 限制实时上游请求数。

curl --fail-with-body -sS 'https://social2api.com/api/run' \
  -H 'Content-Type: application/json' \
  --data-binary @- <<'JSON'
{
  "task": "douyin",
  "mode": "demo",
  "params": {
    "keywords": [
      "露营"
    ],
    "since": "2025-03-03",
    "until": "2025-03-09"
  }
}
JSON

计算上个北京时间自然周并保存结果

将下面保存成 douyin_week.py。先运行 python3 douyin_week.py --as-of 2025-03-10 验收 2025-03-03 至 03-09 的 7 行合成结果。目标目录按模式和日期分开,供 Cron、系统计划任务或 n8n 调用脚本。

生产调度增加 --live --max-requests 2 并从任务的密钥存储注入 SOCIAL2API_API_KEY。生产请求预算在 1–36 次内选定。保留元数据和缺口文件,交付前核对 warnings;成功重复运行更新同一周的文件。

import argparse, csv, json, os
from datetime import date, datetime, timedelta
from pathlib import Path
from urllib.request import Request, urlopen
from zoneinfo import ZoneInfo

parser = argparse.ArgumentParser()
parser.add_argument('--as-of', type=date.fromisoformat)
parser.add_argument('--live', action='store_true')
parser.add_argument('--max-requests', type=int)
options = parser.parse_args()
today = options.as_of or datetime.now(ZoneInfo('Asia/Shanghai')).date()
monday = today - timedelta(days=today.weekday())
since, until = monday - timedelta(days=7), monday - timedelta(days=1)
mode = 'live' if options.live else 'demo'
keywords = ['露营']
params = {'keywords': keywords, 'since': str(since), 'until': str(until)}
body = {'task': 'douyin', 'mode': mode, 'params': params}
headers = {'Content-Type': 'application/json'}
if options.live:
    if options.max_requests is None or not 1 <= options.max_requests <= 36:
        parser.error('--live requires --max-requests in 1–36')
    headers['Authorization'] = 'Bearer ' + os.environ['SOCIAL2API_API_KEY']
    body['maxRequests'] = options.max_requests
request = Request('https://social2api.com/api/run', data=json.dumps(body).encode(), headers=headers)
with urlopen(request, timeout=90) as response:
    result = json.load(response)
if result['mode'] != mode or (mode == 'demo' and result['requestCount'] != 0):
    raise ValueError('Unexpected response mode or usage')
expected = {(word, str(since + timedelta(days=i))) for word in keywords for i in range(7)}
rows = {(row['keyword'], row['date']): row for row in result['rows']}
missing = sorted(expected - rows.keys())
stem = f'douyin-{mode}-{since}-{until}'
Path(stem + '.receipt.json').write_text(json.dumps({'params': params, 'provider': result['provider'],
    'requestCount': result['requestCount'], 'warnings': result['warnings'], 'missing': missing},
    ensure_ascii=False, indent=2), encoding='utf-8')
output = Path(stem + ('-partial.csv' if missing else '.csv'))
temporary = output.with_suffix('.tmp')
with temporary.open('w', encoding='utf-8-sig', newline='') as file:
    writer = csv.DictWriter(file, ['keyword', 'date', 'searchIndex', 'combinedIndex'], extrasaction='ignore')
    writer.writeheader()
    writer.writerows(rows[key] for key in sorted(expected & rows.keys()))
temporary.replace(output)
print(output, 'missing:', len(missing), 'upstream calls:', result['requestCount'])

操作示例与核对

把 2025-03-10 当作本地脚本的固定日期运行一次。上周区间应为 2025-03-03 至 2025-03-09,把两日参数提交 demo 后检查 CSV 日期落在这个区间。

需要核对的字段

keyword、date、searchIndex、combinedIndex、requestCount、warnings。

接口文档

相关用户讨论

打开抖音趋势工作台