Publicar contenido de TikTok sin realizar un seguimiento del rendimiento significa que no puedes identificar qué funciona. Este tutorial crea un rastreador de rendimiento de contenido que obtiene las estadísticas de su video a través de la API Scavio TikTok, almacena instantáneas a lo largo del tiempo y calcula la velocidad de participación (qué tan rápido un video obtiene vistas y me gusta después de su publicación). Utilice estos datos para identificar sus principales patrones de contenido y duplicar lo que resuena. Cada llamada API cuesta $0,005 utilizando la autenticación de token de portador.
Requisitos previos
- Python 3.9+ instalado
- solicita biblioteca instalada
- Una clave API de Scavio de scavio.dev
- Un nombre de usuario de cuenta de TikTok para rastrear
Guia paso a paso
Paso 1: Extrae tu historial de vídeos de TikTok
Obtenga sus publicaciones recientes utilizando el punto final de publicaciones de usuario. Esto devuelve metadatos de video y estadísticas de participación actuales.
import os, requests, json, time
from datetime import datetime
SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
TT_URL = 'https://api.scavio.dev/api/v1/tiktok'
TT_H = {'Authorization': f'Bearer {SCAVIO_KEY}', 'Content-Type': 'application/json'}
def get_user_videos(username: str) -> list:
# Get profile first to get sec_user_id
resp = requests.post(f'{TT_URL}/profile', headers=TT_H,
json={'username': username})
sec_uid = resp.json().get('data', {}).get('user', {}).get('secUid', '')
time.sleep(0.3)
# Get posts
resp = requests.post(f'{TT_URL}/user/posts', headers=TT_H,
json={'sec_user_id': sec_uid, 'count': 30})
videos = resp.json().get('data', {}).get('videos', [])
return [{
'id': v.get('id'),
'desc': v.get('desc', '')[:80],
'created': v.get('createTime', 0),
'views': v.get('stats', {}).get('playCount', 0),
'likes': v.get('stats', {}).get('diggCount', 0),
'comments': v.get('stats', {}).get('commentCount', 0),
'shares': v.get('stats', {}).get('shareCount', 0),
'timestamp': datetime.now().isoformat(),
} for v in videos]
videos = get_user_videos('scikitnews')
print(f'Fetched {len(videos)} videos')
for v in videos[:5]:
print(f' {v["views"]:>10,} views | {v["likes"]:>8,} likes | {v["desc"][:40]}')Paso 2: Almacenar instantáneas para el seguimiento de series temporales
Guarde las estadísticas de video en un archivo JSON con marcas de tiempo. Cada ejecución agrega una nueva instantánea para que pueda realizar un seguimiento de los cambios a lo largo del tiempo.
TRACKING_FILE = 'tiktok_performance.json'
def load_history() -> dict:
if os.path.exists(TRACKING_FILE):
with open(TRACKING_FILE) as f:
return json.load(f)
return {'snapshots': []}
def save_snapshot(videos: list):
history = load_history()
history['snapshots'].append({
'timestamp': datetime.now().isoformat(),
'videos': videos,
})
with open(TRACKING_FILE, 'w') as f:
json.dump(history, f, indent=2)
print(f'Snapshot saved: {len(videos)} videos, {len(history["snapshots"])} total snapshots')
save_snapshot(videos)Paso 3: Calcular la velocidad de interacción
Compare la última instantánea con la anterior para calcular qué tan rápido cada video obtiene vistas y me gusta.
def calculate_velocity(history: dict) -> list:
snapshots = history.get('snapshots', [])
if len(snapshots) < 2:
print('Need at least 2 snapshots to calculate velocity')
return []
current = {v['id']: v for v in snapshots[-1]['videos']}
previous = {v['id']: v for v in snapshots[-2]['videos']}
velocities = []
for vid_id, curr in current.items():
prev = previous.get(vid_id)
if not prev:
continue
view_delta = curr['views'] - prev['views']
like_delta = curr['likes'] - prev['likes']
velocities.append({
'id': vid_id,
'desc': curr['desc'],
'view_velocity': view_delta,
'like_velocity': like_delta,
'total_views': curr['views'],
'engagement_rate': curr['likes'] / curr['views'] if curr['views'] > 0 else 0,
})
velocities.sort(key=lambda x: x['view_velocity'], reverse=True)
print('Content Velocity Report')
print('-' * 60)
for v in velocities[:10]:
print(f' +{v["view_velocity"]:>8,} views | +{v["like_velocity"]:>6,} likes | {v["desc"][:35]}')
return velocities
history = load_history()
calculate_velocity(history)Ejemplo en Python
import os, requests, json, time
from datetime import datetime
SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
TT_H = {'Authorization': f'Bearer {SCAVIO_KEY}', 'Content-Type': 'application/json'}
def track_content(username):
resp = requests.post('https://api.scavio.dev/api/v1/tiktok/profile', headers=TT_H,
json={'username': username})
uid = resp.json().get('data', {}).get('user', {}).get('secUid', '')
time.sleep(0.3)
resp2 = requests.post('https://api.scavio.dev/api/v1/tiktok/user/posts', headers=TT_H,
json={'sec_user_id': uid, 'count': 20})
videos = resp2.json().get('data', {}).get('videos', [])
print(f'Tracking {len(videos)} videos for @{username}')
for v in videos[:5]:
s = v.get('stats', {})
eng = (s.get('diggCount', 0) + s.get('commentCount', 0)) / max(s.get('playCount', 1), 1)
print(f' {s.get("playCount", 0):>10,} views | {eng:.1%} eng | {v.get("desc", "")[:35]}')
track_content('scikitnews')Ejemplo en JavaScript
const SCAVIO_KEY = process.env.SCAVIO_API_KEY;
const TT_H = { Authorization: `Bearer ${SCAVIO_KEY}`, 'Content-Type': 'application/json' };
async function trackContent(username) {
const profile = await fetch('https://api.scavio.dev/api/v1/tiktok/profile', {
method: 'POST', headers: TT_H, body: JSON.stringify({ username })
}).then(r => r.json());
const uid = profile.data?.user?.secUid || '';
const posts = await fetch('https://api.scavio.dev/api/v1/tiktok/user/posts', {
method: 'POST', headers: TT_H, body: JSON.stringify({ sec_user_id: uid, count: 20 })
}).then(r => r.json());
const videos = posts.data?.videos || [];
console.log(`Tracking ${videos.length} videos for @${username}`);
videos.slice(0, 5).forEach(v => {
const s = v.stats || {};
const eng = ((s.diggCount || 0) + (s.commentCount || 0)) / Math.max(s.playCount || 1, 1);
console.log(` ${(s.playCount || 0).toLocaleString()} views | ${(eng * 100).toFixed(1)}% eng`);
});
}
trackContent('scikitnews');Salida esperada
Fetched 30 videos
1,234,567 views | 145,200 likes | How to use search APIs in your app
892,345 views | 98,400 likes | Building an AI agent with web search
654,321 views | 72,100 likes | TikTok API tutorial for developers
Snapshot saved: 30 videos, 2 total snapshots
Content Velocity Report
------------------------------------------------------------
+ 125,000 views | + 14,200 likes | How to use search APIs in your
+ 89,000 views | + 9,800 likes | Building an AI agent with web
+ 45,000 views | + 5,100 likes | TikTok API tutorial for develop