This example demonstrates how to fetch the latest trending videos using TikTokApi.
Requirements:
- You should retrieve an
ms_token from your browser cookies on tiktok.com and provide it via an environment variable or directly in the script. - The library uses asynchronous methods; ensure you use
await and run within an asyncio loop. - You can specify the browser type using the
TIKTOK_BROWSER environment variable (defaults to chromium).
To run the provided example script directly from the repository root:
python -m examples.trending_example
from TikTokApi import TikTokApi
import asyncio
import os
ms_token = os.environ.get("ms_token", None) # 从 tiktok.com 的浏览器 Cookie 中获取你的 ms_token
async def trending_videos():
async with TikTokApi() as api:
await api.create_sessions(ms_tokens=[ms_token], num_sessions=1, sleep_after=3, browser=os.getenv("TIKTOK_BROWSER", "chromium"))
async for video in api.trending.videos(count=30):
print(video)
print(video.as_dict)
if __name__ == "__main__":
asyncio.run(trending_videos())