跳转到正文
Social2api

文档 使用指南 操作指南

50 个抖音关键词怎么分批取数并合并?

Social2api 每次接收最多 20 个去重后的关键词。长词表需要在调用端分批,并保留每批的查询记录。

本页用到的 Social2api 接口

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

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

  1. 清理并去重词表,保留输入原序以及词组归属。
  2. 每 20 项分别提交同一个明确的起止日期,上次响应完成后再运行下一批。
  3. 按 keyword 和 date 合并响应,分别检查各批 warnings 和实际返回日,再导出总表。

复制请求并试跑

先用 20 个合成示例词验证单批上限及词日主键,其余关键词须分成独立请求后汇总。

这条请求使用合成样例,免登录、免 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": "2026-10-01",
    "until": "2026-10-01"
  }
}
JSON

用同一契约完成 20、20、10 个词并合并

把 50 个不同的词逐行放在 keywords.txt。保存脚本,运行 python3 batch_douyin.py,默认合成演练。固定的一日示例应有三批、50 个词日、0 次上游调用。

实时模式需要明确将 SOCIAL2API_MODE 设为 live、设置获 douyin 权限的 Key,并填写每批 SOCIAL2API_MAX_REQUESTS。整个脚本最多可发三批,每批有独立预算。保存回包、缺日和 warnings;失败批次另记,已保存批次可以核对后再补查。

import csv, json, os
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

keywords = list(dict.fromkeys(w.strip() for w in Path('keywords.txt').read_text(encoding='utf-8').splitlines() if w.strip()))
if len(keywords) != 50:
    raise ValueError('Use exactly 50 distinct keywords for this example')
mode = os.environ.get('SOCIAL2API_MODE', 'demo')
if mode not in ('demo', 'live'):
    raise ValueError('Expected demo or live')
headers = {'Content-Type': 'application/json'}
options = {}
if mode == 'live':
    budget = int(os.environ['SOCIAL2API_MAX_REQUESTS'])
    if not 1 <= budget <= 36: raise ValueError('Expected a budget in 1–36')
    options['maxRequests'] = budget
    headers['Authorization'] = 'Bearer ' + os.environ['SOCIAL2API_API_KEY']
day = '2026-10-01'
results, receipts = {}, []
for offset in range(0, len(keywords), 20):
    batch = keywords[offset:offset + 20]
    params = {'keywords': batch, 'since': day, 'until': day}
    payload = {'task': 'douyin', 'mode': mode, 'params': params, **options}
    request = Request('https://social2api.com/api/run', data=json.dumps(payload).encode(), headers=headers)
    try:
        with urlopen(request, timeout=90) as response:
            result = json.load(response)
    except HTTPError as failure:
        receipts.append({'params': params, 'httpStatus': failure.code, 'requestCount': None})
        continue
    except (URLError, TimeoutError, ValueError) as failure:
        receipts.append({'params': params, 'error': type(failure).__name__, 'requestCount': None})
        continue
    if result.get('mode') != mode or not isinstance(result.get('rows'), list):
        receipts.append({'params': params, 'error': 'unexpected response', 'requestCount': None})
        continue
    Path(f'douyin-{mode}-batch-{offset // 20 + 1}.json').write_text(json.dumps(result, ensure_ascii=False), encoding='utf-8')
    for row in result['rows']:
        results[row['keyword'], row['date']] = row
    receipts.append({'params': params, 'provider': result['provider'],
                     'warnings': result['warnings'], 'requestCount': result['requestCount']})
with open(f'douyin-{mode}-merged.csv', 'w', encoding='utf-8-sig', newline='') as file:
    writer = csv.DictWriter(file, ['keyword', 'date', 'searchIndex', 'combinedIndex'], extrasaction='ignore')
    writer.writeheader()
    writer.writerows(results[key, day] for key in keywords if (key, day) in results)
receipt = {'batches': receipts, 'missing': [key for key in keywords if (key, day) not in results],
           'knownRequestCount': sum(batch['requestCount'] for batch in receipts if batch['requestCount'] is not None),
           'batchesWithUnknownUsage': sum(batch['requestCount'] is None for batch in receipts)}
Path(f'douyin-{mode}-receipt.json').write_text(json.dumps(receipt, ensure_ascii=False, indent=2), encoding='utf-8')

操作示例与核对

把可用的 50 个真实词切成 20、20、10 三个任务。先用 mode 为 demo 验证每批输入及日期键,合成结果只用于核对汇总流程。

需要核对的字段

params.keywords、params.since、params.until、rows[].keyword、rows[].date、warnings、requestCount。

接口文档

相关用户讨论

打开抖音趋势工作台