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

[规范网址](https://social2api.com/guides/douyin-keyword-trends-weekly-scheduled-export/)

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

## Agent 提示词

~~~~text
请在 Social2api 使用抖音关键词逐日趋势，执行以下任务。
目标：外部计划任务计算北京时间上周窗口并归档成功结果。
输入与对照示例：把 2025-03-10 当作本地脚本的固定日期运行一次。上周区间应为 2025-03-03 至 2025-03-09，把两日参数提交 demo 后检查 CSV 日期落在这个区间。
公开查询可先用免密钥合成示例；实时取数需要权限和部署支持。
按以下步骤完成：用 Python 的 ZoneInfo("Asia/Shanghai") 计算当天日期，取本周一，再分别减 7 天和 1 天作为上周起止日。 计划任务调用 POST /api/run，固定词表和日期。先用 demo 检查调度环境与解析，实时请求在已配置密钥和额度后运行。 检查 HTTP 状态、warnings 和关键词覆盖。演示的合成数据提示为预期输出。实时结果先写临时文件，再写入含起止日的最终路径；有缺口时为这周单独留异常记录。
交付能核对的结果和必要字段：keyword、date、searchIndex、combinedIndex、requestCount、warnings。注明来源或限制，并以本页为操作参考。
https://social2api.com/guides/douyin-keyword-trends-weekly-scheduled-export/
~~~~

[打开抖音趋势工作台](https://social2api.com/#workspace/douyin)

[查看对应 API](https://social2api.com/docs/api/douyin-keyword-trends/)

## 本页用到的 Social2api 接口

| 接口与参数文档 | 用途 |
| --- | --- |
| [抖音关键词逐日趋势](https://social2api.com/docs/api/douyin-keyword-trends/) · 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 限制实时上游请求数。

~~~~bash
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；成功重复运行更新同一周的文件。

~~~~python
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。

## 接口文档

- [抖音关键词逐日趋势](https://social2api.com/docs/api/douyin-keyword-trends/)
- [怎么批量获取过去 30 天的抖音关键词搜索热度？](https://social2api.com/guides/douyin-keyword-trends-30-days/)

## 相关用户讨论

- [相邻平台类比 · YouTube、TikTok、Instagram、Facebook、Threads · 约 20 个社媒账号分别分布在 YouTube、TikTok、Instagram、Facebook 和 Threads，如何每周追踪各账号表现？](https://www.reddit.com/r/SocialMediaManagers/comments/1rp4sal/)
- [相邻平台类比 · 跨平台社媒 · 社媒运营怎样组织日常内容研究、观察竞品和热点，持续走在变化前面？](https://www.reddit.com/r/SocialMediaManagers/comments/1km2a3p/)
- [相邻平台类比 · Instagram · 怎样每月将 Instagram 全部帖子及发布时间、点赞和评论计数导入 Google Sheets？不需要评论正文或互动者信息。](https://www.reddit.com/r/socialmedia/comments/1igv6h6/)

## 相关指南和问答

- [怎么批量获取过去 30 天的抖音关键词搜索热度？](https://social2api.com/guides/douyin-keyword-trends-30-days/)

[打开抖音趋势工作台](https://social2api.com/#workspace/douyin)
