API List
Note
🟢 Indicates implemented, 🟡 Indicates in progress or being modified, 🟤 Indicates temporarily not implemented, 🔵 Indicates possible future implementation, 🔴 Indicates deprecation.
handler API List
CLI Interface | Method |
---|---|
Download a single video | handle_one_video |
Download user posts | handle_user_post |
Download user likes | handle_user_like |
Download user favorites | handle_user_collect |
Download user playlist | handle_user_mix |
Download search videos | handle_search_video |
Download user live stream | handle_user_live |
Data & Function APIs | Method | Developer API |
---|---|---|
User profile | fetch_user_profile | 🟢 |
Create user record & folder | get_or_add_user_data | 🟢 |
Create video download record | get_or_add_video_data | 🟢 |
Fetch single video data | fetch_one_video | 🟢 |
Fetch user posts data | fetch_user_post_videos | 🟢 |
Fetch user liked videos | fetch_user_like_videos | 🟢 |
Fetch user favorites | fetch_user_collect_videos | 🟢 |
Fetch user playlists | fetch_play_list | 🟢 |
Fetch user playlist videos | fetch_user_mix_videos | 🟢 |
Fetch search results | fetch_search_videos | 🟢 |
Fetch user live stream | fetch_user_live_videos | 🟢 |
Check live stream status | fetch_check_live_alive | 🟢 |
utils API List
Developer API | Class Name | Method | Status |
---|---|---|---|
Manage client config | ClientConfManager | 🟢 | |
Generate real msToken | TokenManager | gen_real_msToken | 🟢 |
Generate fake msToken | TokenManager | gen_false_msToken | 🟢 |
Generate ttwid | TokenManager | gen_ttwid | 🟢 |
Generate odin_tt | TokenManager | gen_odin_tt | 🟢 |
Generate Xb params from URL | XBogusManager | str_2_endpoint | 🟢 |
Generate Xb params from model | XBogusManager | model_2_endpoint | 🟢 |
Extract single user ID | SecUserIdFetcher | get_secuid | 🟢 |
Extract list of user IDs | SecUserIdFetcher | get_all_secuid | 🟢 |
Extract single unique user ID | SecUserIdFetcher | get_uniqueid | 🟢 |
Extract list of unique user IDs | SecUserIdFetcher | get_all_uniqueid | 🟢 |
Extract list of user IDs | SecUserIdFetcher | get_all_secUid | 🟢 |
Extract single video ID | AwemeIdFetcher | get_aweme_id | 🟢 |
Extract list of video IDs | AwemeIdFetcher | get_all_aweme_id | 🟢 |
Generate device ID | DeviceIdManager | gen_device_id | 🟢 |
Generate list of device IDs | DeviceIdManager | gen_device_ids | 🟢 |
Global file name formatting | - | format_file_name | 🟢 |
Create user folder | - | create_user_folder | 🟢 |
Rename user folder | - | rename_user_folder | 🟢 |
Create or rename user folder | - | create_or_rename_user_folder | 🟢 |
crawler API List
Crawler URL API | Class Name | Method | Status |
---|---|---|---|
User profile API | TiktokCrawler | fetch_user_profile | 🟢 |
User posts API | TiktokCrawler | fetch_user_post | 🟢 |
User likes API | TiktokCrawler | fetch_user_like | 🟢 |
User favorites API | TiktokCrawler | fetch_user_collect | 🟢 |
User playlist API | TiktokCrawler | fetch_user_play_list | 🟢 |
Playlist videos API | TiktokCrawler | fetch_user_mix | 🟢 |
Video details API | TiktokCrawler | fetch_post_detail | 🟢 |
Video comments API | TiktokCrawler | fetch_post_comment | 🟢 |
Homepage feed API | TiktokCrawler | fetch_post_feed | 🟢 |
Search videos API | TiktokCrawler | fetch_post_search | 🟢 |
User live stream API | TiktokCrawler | fetch_user_live | 🟢 |
Check live stream status API | TiktokCrawler | fetch_check_live_alive | 🟢 |
dl API List
Downloader API | Class Name | Method | Status |
---|---|---|---|
Save last downloaded video ID | TiktokDownloader | save_last_aweme_id | 🟢 |
Filter videos by time range | TiktokDownloader | filter_aweme_datas_by_interval | 🟢 |
Create download task | TiktokDownloader | create_download_task | 🟢 |
Handle download task | TiktokDownloader | handle_download | 🟢 |
Create stream download task | TiktokDownloader | create_stream_tasks | 🟢 |
Handle stream download task | TiktokDownloader | handle_stream | 🟢 |
💡 Tip
- Pagination parameters are included in the response from the previous request, making it easy to filter results using the built-in
filter
. - All APIs with pagination use asynchronous generators, requiring iteration with
async for
for automatic pagination handling. - If
max_counts
is set toNone
or omitted, all available video data will be fetched. - These APIs can be easily integrated into backend frameworks like
FastAPI
,Flask
, andDjango
. - Using a logged-in
cookie
allows bypassing privacy restrictions, such as privatevideos
,profile
,likes
, andfavorites
.
Handler Interface List
Single Video Data 🟢
Asynchronous method to retrieve a single video.
Parameter | Type | Description |
---|---|---|
aweme_id | str | Video ID |
Return | Type | Description |
---|---|---|
video_data | dict | Dictionary containing video data, including video ID, caption, author nickname, etc. |
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"cookie": "YOUR_COOKIE_HERE",
}
async def main():
video = await TiktokHandler(kwargs).fetch_one_video(itemId="7095819783324601605")
print("=================_to_raw================")
print(video._to_raw())
# print("=================_to_dict================")
# print(video._to_dict())
# print("=================_to_list================")
# print(video._to_list())
if __name__ == "__main__":
asyncio.run(main())
User Published Videos 🟢
Asynchronous method to retrieve a list of videos published by a user.
Parameter | Type | Description |
---|---|---|
secUid | str | User ID |
cursor | int | Page number, default is 0 |
page_counts | int | Number of pages, default is 20 |
max_counts | int | Maximum number of pages, default is None |
Return | Type | Description |
---|---|---|
aweme_data | dict | Dictionary containing video data, including video ID, caption, author nickname, page number, etc. |
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import SecUserIdFetcher
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"timeout": 10,
"cookie": "YOUR_COOKIE_HERE",
}
async def main():
secUid = await SecUserIdFetcher.get_secuid("https://www.tiktok.com/@vantoan___")
async for aweme_data_list in TiktokHandler(kwargs).fetch_user_post_videos(
secUid, 0, 0, 10, 20
):
print("=================_to_raw================")
print(aweme_data_list._to_raw())
# print("=================_to_dict===============")
# print(aweme_data_list._to_dict())
# print("=================_to_list===============")
# print(aweme_data_list._to_list())
if __name__ == "__main__":
asyncio.run(main())
User Liked Videos 🟢
Asynchronous method to retrieve a list of videos liked by a specified user. The like list must be public.
Parameter | Type | Description |
---|---|---|
secUid | str | User ID |
cursor | int | Page number, default is 0 |
page_counts | int | Number of pages, default is 20 |
max_counts | int | Maximum number of pages, default is None |
Return | Type | Description |
---|---|---|
aweme_data | dict | Dictionary containing video data, including video ID, caption, author nickname, page number, etc. |
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import SecUserIdFetcher
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"timeout": 10,
"cookie": "YOUR_COOKIE_HERE",
}
async def main():
secUid = await SecUserIdFetcher.get_secuid(
"YOUR_HOME_PAGE"
) # 替换开放喜欢列表的用户主页
async for user_like_list in TiktokHandler(kwargs).fetch_user_like_videos(
secUid, 0, 10, 20
):
print("=================_to_raw================")
print(user_like_list._to_raw())
# print("=================_to_dict===============")
# print(user_like_list._to_dict())
# print("=================_to_list===============")
# print(user_like_list._to_list())
if __name__ == "__main__":
asyncio.run(main())
User Collected Videos 🟢
Asynchronous method to retrieve a list of videos collected by a specified user.
Parameter | Type | Description |
---|---|---|
secUid | str | User ID |
cursor | int | Page number, default is 0 |
page_counts | int | Number of pages, default is 20 |
max_counts | int | Maximum number of pages, default is None |
Return | Type | Description |
---|---|---|
aweme_data | dict | Dictionary containing video data, including video ID, caption, author nickname, page number, etc. |
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import SecUserIdFetcher
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"timeout": 10,
"cookie": "YOUR_COOKIE_HERE",
}
async def main():
secUid = await SecUserIdFetcher.get_secuid(
"YOUR_HOME_PAGE"
) # 替换开放收藏列表的用户主页
async for collect_list in TiktokHandler(kwargs).fetch_user_collect_videos(
secUid, 0, 10, 20
):
print("=================_to_raw================")
print(collect_list._to_raw())
# print("=================_to_dict===============")
# print(collect_list._to_dict())
# print("=================_to_list===============")
# print(collect_list._to_list())
if __name__ == "__main__":
asyncio.run(main())
User Playlist Videos 🟢
Asynchronous method to retrieve a list of videos from a specified user's playlist.
Parameter | Type | Description |
---|---|---|
secUid | str | Collection ID |
cursor | int | Page number, default is 0 |
page_counts | int | Number of pages, default is 20 |
Return | Type | Description |
---|---|---|
aweme_data | dict | Dictionary containing video data, including video ID, caption, author nickname, page number, etc. |
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import SecUserIdFetcher
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"cookie": "YOUR_COOKIE_HERE",
}
async def main():
secUid = await SecUserIdFetcher.get_secuid("https://www.tiktok.com/@vantoan___")
playlist = await TiktokHandler(kwargs).fetch_play_list(secUid, 0, 30)
print("=================_to_raw================")
print(playlist._to_raw())
# print("=================_to_dict===============")
# print(aweme_data_list._to_dict())
if __name__ == "__main__":
asyncio.run(main())
User Collection Videos 🟢
Asynchronous method to retrieve a list of videos from a specified user collection. The mix_id
for all collection videos remains the same and can be retrieved from the single video data interface.
Parameter | Type | Description |
---|---|---|
mixId | str | Collection ID |
cursor | int | Page number, default is 0 |
page_counts | int | Number of pages, default is 20 |
max_counts | int | Maximum number of pages, default is None |
Return | Type | Description |
---|---|---|
aweme_data | dict | Dictionary containing video data, including video ID, caption, author nickname, page number, etc. |
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import SecUserIdFetcher
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"timeout": 10,
"cookie": "YOUR_COOKIE_HERE",
}
async def main():
secUid = await SecUserIdFetcher.get_secuid("https://www.tiktok.com/@vantoan___")
playlist = await TiktokHandler(kwargs).fetch_play_list(
secUid,
cursor=0,
page_counts=20,
)
for mixId in playlist._to_dict().get("mixId", []):
async for user_mix_list in TiktokHandler(kwargs).fetch_user_mix_videos(
mixId,
cursor=0,
page_counts=20,
max_counts=20,
):
print("=================_to_raw================")
print(user_mix_list._to_raw())
# print("=================_to_dict===============")
# print(user_mix_list._to_dict())
# print("=================_to_list===============")
# print(user_mix_list._to_list())
if __name__ == "__main__":
asyncio.run(main())
Note
Multiple playlists may contain multiple mix_id
values. Use the select_playlist
method to return the index of the user-selected collection.
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"timeout": 10,
"cookie": "YOUR_COOKIE_HERE",
}
async def main():
secUid = await SecUserIdFetcher.get_secuid("https://www.tiktok.com/@vantoan___")
playlist = await TiktokHandler(kwargs).fetch_play_list(secUid)
selected_index = await TiktokHandler(kwargs).select_playlist(
playlist
)
if selected_index != 0:
mixId = playlist.get("mixId", [])[selected_index - 1]
async for aweme_data_list in TiktokHandler(kwargs).fetch_user_mix_videos(mixId):
print(aweme_data_list._to_raw())
# print("=================_to_dict===============")
# print(aweme_data_list._to_dict())
# print("=================_to_list===============")
# print(aweme_data_list._to_list())
if __name__ == "__main__":
asyncio.run(main())
User Profile 🟢
Asynchronous method to retrieve a specified user's profile information. The data from Filter
cannot be parsed directly; use custom _to_dict
or _to_list
methods.
Parameter | Type | Description |
---|---|---|
secUid | str | User ID |
uniqueId | str | User ID |
Return | Type | Description |
---|---|---|
UserProfileFilter | model | Custom interface data filter |
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"cookie": "YOUR_COOKIE_HERE",
}
async def main():
secUid = (
"MS4wLjABAAAAQhcYf_TjRKUku-aF8oqngAfzrYksgGLRz8CKMciBFdfR54HQu3qGs-WoJ-KO7hO8"
)
uniqueId = "vantoan___"
user = await TiktokHandler(kwargs).fetch_user_profile(secUid=secUid)
print("=================_to_raw================")
print(user._to_raw())
# print("=================_to_dict===============")
# print(user._to_dict())
user = await TiktokHandler(kwargs).fetch_user_profile(uniqueId=uniqueId)
print("=================_to_raw================")
print(user._to_raw())
# print("=================_to_dict===============")
# print(user._to_dict())
if __name__ == "__main__":
asyncio.run(main())
💡 Hint
TikTok's user interface supports both secUid
and uniqueId
as user IDs.
Create User Record and Directory 🟢
Asynchronous method to fetch or create user data while creating a user directory.
Parameter | Type | Description |
---|---|---|
kwargs | dict | cli dictionary data, requires the path parameter |
secUid | str | User ID |
db | AsyncUserDB | User database |
Return | Type | Description |
---|---|---|
user_path | Path | User directory path object |
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.db import AsyncUserDB
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"cookie": "YOUR_COOKIE_HERE",
"path": "Download",
}
async def main():
async with AsyncUserDB("tiktok_users.db") as audb:
secUid = "MS4wLjABAAAAQhcYf_TjRKUku-aF8oqngAfzrYksgGLRz8CKMciBFdfR54HQu3qGs-WoJ-KO7hO8"
print(
await TiktokHandler(kwargs).get_or_add_user_data(
kwargs=kwargs, secUid=secUid, db=audb
)
)
if __name__ == "__main__":
asyncio.run(main())
💡 Hint
This is an interface for cli
mode. Developers can define their own functions to create user directories.
Create Video Download Record 🟢
Asynchronous method to fetch or create video data while creating a video directory.
Parameter | Type | Description |
---|---|---|
aweme_data | dict | Video data dictionary |
db | AsyncVideoDB | Video database |
ignore_fields | list | List of fields to ignore |
Return | Type | Description |
---|---|---|
None | None | None |
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.db import AsyncVideoDB
# 需要忽略的字段(需过滤掉有时效性的字段)
ignore_fields = ["video_play_addr", "images", "video_bit_rate", "cover"]
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"cookie": "YOUR_COOKIE_HERE",
}
async def main():
aweme_data = await TiktokHandler(kwargs).fetch_one_video(
itemId="7095819783324601605"
)
async with AsyncVideoDB("tiktok_videos.db") as avdb:
await TiktokHandler(kwargs).get_or_add_video_data(
aweme_data._to_dict(), avdb, ignore_fields
)
if __name__ == "__main__":
asyncio.run(main())
Utils Interface List
Manage Client Configuration 🟢
Class method to manage client configuration.
Parameter | Type | Description |
---|---|---|
None | None | None |
Return | Type | Description |
---|---|---|
Config Value | Any | Configuration file value |
from f2.apps.tiktok.utils import ClientConfManager
if __name__ == "__main__":
print("Client Configuration:")
print(ClientConfManager.client())
print("Client Configuration version:")
print(ClientConfManager.conf_version())
print("Client Configuration user-agent:")
print(ClientConfManager.user_agent())
Generate Real msToken
🟢
Class method to generate a real msToken
. Returns a fake value in case of errors.
Parameter | Type | Description |
---|---|---|
None | None | None |
Return | Type | Description |
---|---|---|
msToken | str | Real msToken |
from f2.apps.tiktok.utils import TokenManager
if __name__ == "__main__":
print("tiktok real msToken:", TokenManager.gen_real_msToken())
Generate Fake msToken
🟢
Class method to generate a randomly faked msToken
. The length of msToken
varies across endpoints.
Parameter | Type | Description |
---|---|---|
None | None | None |
Return | Type | Description |
---|---|---|
msToken | str | Fake msToken |
from f2.apps.tiktok.utils import TokenManager
if __name__ == "__main__":
print("tiktok fake msToken:", TokenManager.gen_false_msToken())
💡 Hint
The default length is 126 characters
. You can also call from f2.utils.utils import gen_random_str
to generate a fake msToken
of a different length.
Generate ttwid
🟢
Class method to generate ttwid
, which is required for certain requests.
Parameter | Type | Description |
---|---|---|
None | None | None |
Return | Type | Description |
---|---|---|
ttwid | str | ttwid parameter |
from f2.apps.tiktok.utils import TokenManager
if __name__ == "__main__":
print("tiktok ttwid:", TokenManager.gen_ttwid())
⚠️ Warning
The ttwid
value in the configuration file is a new ttwid
cookie. If it expires, replace it with a new ttwid
value.
Generate odin_tt 🟢
Class method for generating odin_tt
, required for some requests.
Parameter | Type | Description |
---|---|---|
None | None | None |
Return | Type | Description |
---|---|---|
odin_tt | str | The odin_tt parameter |
from f2.apps.tiktok.utils import TokenManager
if __name__ == "__main__":
print("tiktok odin_tt:", TokenManager.gen_odin_tt())
⚠️ Note
The odin_tt
parameter in the configuration file is fixed and cannot be changed.
Generate Xb Parameter Using API Endpoint 🟢
Class method for directly generating the Xbogus
parameter using an API endpoint. Some APIs do not require validation.
Parameter | Type | Description |
---|---|---|
endpoint | str | API endpoint |
Return | Type | Description |
---|---|---|
final_endpoint | str | The complete API URL with Xbogus parameter |
# 使用接口地址直接生成请求链接
from f2.apps.tiktok.utils import XBogusManager
def main():
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"
test_endpoint = "aid=1988&app_language=zh-Hans&app_name=tiktok_web&browser_platform=Win32&browser_version=5.0%20%28Windows%20NT%2010.0%3B%20Win64%3B%20x64%29%20AppleWebKit%2F537.36%20%28KHTML%2C%20like%20Gecko%29%20Chrome%2F120.0.0.0%20Safari%2F537.36&channel=tiktok_web&cookie_enabled=true&count=16&coverFormat=2&device_id=7306060721837852167&device_platform=web_pc&itemID=7294298719665622305"
return XBogusManager.str_2_endpoint(user_agent, test_endpoint)
if __name__ == "__main__":
print(main())
Generate Xb Parameter Using API Model 🟢
Class method for generating the Xbogus
parameter using different API data models. Some APIs do not require validation.
Parameter | Type | Description |
---|---|---|
endpoint | str | API endpoint |
params | dict | Request parameters |
Return | Type | Description |
---|---|---|
final_endpoint | str | The complete API URL with Xbogus parameter |
To generate an endpoint using a model, create a model object and call the model_2_endpoint
method.
# 使用用户信息模型生成请求链接
import asyncio
from f2.apps.tiktok.api import TiktokAPIEndpoints as tkendpoint
from f2.apps.tiktok.model import UserProfile
from f2.apps.tiktok.utils import XBogusManager
async def gen_user_profile(params: UserProfile):
return XBogusManager.model_2_endpoint(tkendpoint.USER_DETAIL, params.model_dump())
async def main():
secUid = (
"MS4wLjABAAAAQhcYf_TjRKUku-aF8oqngAfzrYksgGLRz8CKMciBFdfR54HQu3qGs-WoJ-KO7hO8"
)
params = UserProfile(secUid=secUid)
return await gen_user_profile(params)
if __name__ == "__main__":
print(asyncio.run(main()))
Data collection is also possible using a crawler engine with a filter.
# 使用用户信息模型生成请求链接,请求接口并使用自定义过滤器输出所需接口数据
import asyncio
from f2.apps.tiktok.api import TiktokAPIEndpoints as tkendpoint
from f2.apps.tiktok.crawler import TiktokCrawler
from f2.apps.tiktok.model import UserProfile
from f2.apps.tiktok.filter import UserProfileFilter
from f2.apps.tiktok.utils import XBogusManager
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"cookie": "YOUR_COOKIE_HERE",
}
async def main():
async with TiktokCrawler(kwargs) as crawler:
secUid = "MS4wLjABAAAAQhcYf_TjRKUku-aF8oqngAfzrYksgGLRz8CKMciBFdfR54HQu3qGs-WoJ-KO7hO8"
params = UserProfile(secUid=secUid)
response = await crawler.fetch_user_profile(params)
user = UserProfileFilter(response)
# return user # user为UserProfileFilter对象,需要调用_to_dict()方法转为字典格式
return user._to_dict()
if __name__ == "__main__":
print(asyncio.run(main()))
For more advanced use cases, call fetch_user_profile
from the handler
interface.
Extract Single User ID 🟢
Class method to extract a single user ID.
Parameter | Type | Description |
---|---|---|
url | str | User profile URL |
Return | Type | Description |
---|---|---|
sec_uid | str | User ID |
import asyncio
from f2.apps.tiktok.utils import SecUserIdFetcher
async def main():
raw_url = "https://www.tiktok.com/@vantoan___"
# 对于单个URL
return await SecUserIdFetcher.get_secuid(raw_url)
if __name__ == "__main__":
print(asyncio.run(main()))
Extract Multiple User IDs 🟢
Class method to extract multiple user IDs.
Parameter | Type | Description |
---|---|---|
urls | list | List of user profile URLs |
Return | Type | Description |
---|---|---|
secuids | list | List of user IDs |
import asyncio
from f2.apps.tiktok.utils import SecUserIdFetcher
from f2.utils.utils import extract_valid_urls
async def main():
raw_urls = [
"https://www.tiktok.com/@vantoan___/",
"https://www.tiktok.com/@vantoan___?is_from_webapp=1&sender_device=pc",
# "https://vt.tiktok.com/xxxxxxxxxx/"
]
# 提取有效URL
urls = extract_valid_urls(raw_urls)
# 对于URL列表
return await SecUserIdFetcher.get_all_secuid(urls)
if __name__ == "__main__":
print(asyncio.run(main()))
Extract Single Unique User ID 🟢
Class method to extract a single unique user ID.
Parameter | Type | Description |
---|---|---|
url | str | User profile URL |
Return | Type | Description |
---|---|---|
unique_id | str | Unique user ID |
import asyncio
from f2.apps.tiktok.utils import SecUserIdFetcher
async def main():
raw_url = "https://www.tiktok.com/@vantoan___"
# 对于单个URL
return await SecUserIdFetcher.get_uniqueid(raw_url)
if __name__ == "__main__":
print(asyncio.run(main()))
Extract Multiple Unique User IDs 🟢
Class method to extract multiple unique user IDs.
Parameter | Type | Description |
---|---|---|
urls | list | List of user profile URLs |
Return | Type | Description |
---|---|---|
unique_ids | list | List of unique user IDs |
import asyncio
from f2.apps.tiktok.utils import SecUserIdFetcher
from f2.utils.utils import extract_valid_urls
async def main():
raw_urls = [
"https://www.tiktok.com/@vantoan___/",
"https://www.tiktok.com/@vantoan___?is_from_webapp=1&sender_device=pc",
# "https://vt.tiktok.com/xxxxxxxxxx/"
]
# 提取有效URL
urls = extract_valid_urls(raw_urls)
# 对于URL列表
return await SecUserIdFetcher.get_all_uniqueid(urls)
if __name__ == "__main__":
print(asyncio.run(main()))
Extract Single Video ID 🟢
Class method to extract a single video ID.
Parameter | Type | Description |
---|---|---|
url | str | Video URL |
Return | Type | Description |
---|---|---|
aweme_id | str | Video ID |
import asyncio
from f2.apps.tiktok.utils import AwemeIdFetcher
async def main():
raw_url = "https://www.tiktok.com/@vantoan___/video/7283528426256911649"
# 支持短链解析但其具有时效性,故不举例
return await AwemeIdFetcher.get_aweme_id(raw_url)
if __name__ == "__main__":
print(asyncio.run(main()))
Extract Multiple Video IDs 🟢
Class method to extract multiple video IDs.
Parameter | Type | Description |
---|---|---|
urls | list | List of video URLs |
Return | Type | Description |
---|---|---|
aweme_ids | list | List of video IDs |
import asyncio
from f2.apps.tiktok.utils import AwemeIdFetcher
from f2.utils.utils import extract_valid_urls
async def main():
raw_urls = [
"https://www.tiktok.com/@vantoan___/video/7316948869764484384",
"https://www.tiktok.com/@vantoan___/video/7316948869764484384?is_from_webapp=1&sender_device=pc&web_id=7306060721837852167",
# 支持短链解析但其具有时效性,故不举例
]
# 提取有效URL
urls = extract_valid_urls(raw_urls)
# 对于URL列表
return await AwemeIdFetcher.get_all_aweme_id(urls)
if __name__ == "__main__":
print(asyncio.run(main()))
💡 Tip
Both web and app-shared links are valid.
Generate Device ID 🟢
Class method to generate deviceId
and tt_chain_token
.
Parameter | Type | Description |
---|---|---|
full_cookie | bool | Whether to return the full cookie |
Return | Type | Description |
---|---|---|
device_id | dict | Dictionary containing device ID and cookie |
import asyncio
from f2.apps.tiktok.utils import DeviceIdManager
async def main():
device_id = await DeviceIdManager.gen_device_id()
print("device_id:", device_id.get("deviceId"), "cookie:", device_id.get("cookie"))
device_id = await DeviceIdManager.gen_device_id(full_cookie=True)
print("device_id:", device_id.get("deviceId"), "cookie:", device_id.get("cookie"))
if __name__ == "__main__":
asyncio.run(main())
Generate Multiple Device IDs 🟢
Class method to generate multiple deviceId
and tt_chain_token
values.
Parameter | Type | Description |
---|---|---|
count | int | Number of device IDs |
full_cookie | bool | Whether to return the full cookie |
Return | Type | Description |
---|---|---|
device_ids | dict | Dictionary containing multiple device IDs and cookies |
import asyncio
from f2.apps.tiktok.utils import DeviceIdManager
async def main():
device_ids = await DeviceIdManager.gen_device_ids(3)
print(
"device_ids:", device_ids.get("deviceId"), "cookies:", device_ids.get("cookie")
)
device_ids = await DeviceIdManager.gen_device_ids(3, full_cookie=True)
print(
"device_ids:", device_ids.get("deviceId"), "cookies:", device_ids.get("cookie")
)
if __name__ == "__main__":
asyncio.run(main())
💡 Tip
deviceId
and tt_chain_token
parameters are bound to the configuration file and affect video access. A 403
error usually indicates an issue with these parameters.
Global Filename Formatting 🟢
Formats filenames globally based on the configuration file.
📄 Filename Formatting Rules
Windows
: Filename length is limited to255
characters (or32,767
with long filename support).Unix
: Filename length is limited to255
characters.- Truncates to
20
characters, plus suffix, to stay within the255
limit. - Developers can customize
custom_fields
to define their own filenames.
Parameter | Type | Description |
---|---|---|
naming_template | str | Filename template |
aweme_data | dict | Video metadata |
custom_fields | dict | Custom fields for replacing default values |
Return | Type | Description |
---|---|---|
file_name | str | Formatted filename |
import asyncio
from f2.apps.tiktok.handler import TiktokHandler
from f2.apps.tiktok.utils import format_file_name
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"cookie": "YOUR_COOKIE_HERE",
"naming": "{create}_{desc}_{aweme_id}",
}
async def main():
# 单作品的数据
aweme_data = await TiktokHandler(kwargs).fetch_one_video("7316948869764484384")
# 格式化后的文件名
print(format_file_name(kwargs.get("naming"), aweme_data._to_dict()) + "_video")
# 文件名模板
kwargs = {
# ...
"naming": "{create}_{desc}_{aweme_id}_{location}",
# ...
}
# 用户自定义字段
custom_fields = {"location": "New York"}
# 格式化后的自定义文件名
print(
format_file_name(kwargs.get("naming"), aweme_data._to_dict(), custom_fields)
+ "_video"
)
if __name__ == "__main__":
asyncio.run(main())
Create User Directory 🟢
Creates a user directory if it does not already exist.
📂 User Directory Structure
If no path is specified in the configuration file, the default is Download
. Both absolute and relative paths are supported.
├── Download
│ ├── tiktok
│ │ ├── post
│ │ │ ├── user_nickname
│ │ │ │ ├── 2023-12-31_23-59-59_desc
│ │ │ │ │ ├── 2023-12-31_23-59-59_desc-video.mp4
│ │ │ │ │ ├── 2023-12-31_23-59-59_desc-desc.txt
│ │ │ │ │ └── ......
│ │ ├── like
│ │ ├── ...
Parameter | Type | Description |
---|---|---|
kwargs | dict | cli configuration file |
nickname | Union[str, int] | User nickname |
Return | Type | Description |
---|---|---|
user_path | Path | User directory path object |
from f2.apps.tiktok.utils import create_user_folder
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"cookie": "YOUR_COOKIE_HERE",
"path": "Download",
"mode": "post",
}
if __name__ == "__main__":
current_nickname = "New Nickname"
print(create_user_folder(kwargs, current_nickname))
# X:\......\Download\tiktok\post\New Nickname
Rename User Directory 🟢
Used to rename a user directory.
Parameter | Type | Description |
---|---|---|
old_path | Path | Old user directory path object |
new_nickname | str | New user nickname |
Return | Type | Description |
---|---|---|
new_path | Path | New user directory path object |
import asyncio
from f2.apps.tiktok.db import AsyncUserDB
from f2.apps.tiktok.utils import rename_user_folder
from f2.apps.tiktok.handler import TiktokHandler
kwargs = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
"Referer": "https://www.tiktok.com/",
},
"proxies": {"http://": None, "https://": None},
"cookie": "YOUR_COOKIE_HERE",
"path": "Download",
"mode": "post",
}
async def main():
sec_user_id = (
"MS4wLjABAAAAQhcYf_TjRKUku-aF8oqngAfzrYksgGLRz8CKMciBFdfR54HQu3qGs-WoJ-KO7hO8"
)
async with AsyncUserDB("tiktok_users.db") as audb:
local_user_path = await TiktokHandler(kwargs).get_or_add_user_data(
sec_user_id, audb
)
print(local_user_path)
# X:\......\Download\tiktok\post\vantoan___
current_nickname = "New Nickname"
new_user_path = rename_user_folder(local_user_path, current_nickname)
print(new_user_path)
# X:\......\Download\tiktok\post\New Nickname
if __name__ == "__main__":
asyncio.run(main())
💡 Note
If the directory does not exist, it will be created before renaming.
Create or Rename User Directory 🟢
Used to create or rename a user directory. This is a combination of the two interfaces above.
Parameter | Type | Description |
---|---|---|
kwargs | dict | cli configuration file |
local_user_data | dict | Local user data |
current_nickname | str | Current user nickname |
Return | Type | Description |
---|---|---|
user_path | Path | User directory path object |
💡 Note
This interface effectively resolves the issue of duplicate downloads when a user changes their nickname. It is integrated into the get_or_add_user_data
method in the handler interface, so developers can call the handler’s data interface directly without worrying about this issue.
crawler Interface
User Profile API Endpoint 🟢
API endpoint for retrieving user profile information.
Parameter | Type | Description |
---|---|---|
UserProfile | model | User profile API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch user profile information |
User Posts API Endpoint 🟢
API endpoint for retrieving a user's posted videos.
Parameter | Type | Description |
---|---|---|
UserPost | model | User post API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch user posts |
Liked Posts API Endpoint 🟢
API endpoint for retrieving a user's liked videos.
Parameter | Type | Description |
---|---|---|
UserLike | model | User liked posts API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch liked posts |
Collected Posts API Endpoint 🟢
API endpoint for retrieving a user's collected videos.
Parameter | Type | Description |
---|---|---|
UserCollect | model | User collected posts API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch collected posts |
Playlist API Endpoint 🟢
API endpoint for retrieving a user's playlist.
Parameter | Type | Description |
---|---|---|
UserPlayList | model | User playlist API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch user playlists |
Playlist Videos API Endpoint 🟢
API endpoint for retrieving videos in a user's playlist.
Parameter | Type | Description |
---|---|---|
UserMix | model | User playlist videos API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch playlist videos |
Post Detail API Endpoint 🟢
API endpoint for retrieving post details.
Parameter | Type | Description |
---|---|---|
PostDetail | model | Post detail API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch post details |
Post Comments API Endpoint 🟢
API endpoint for retrieving post comments.
Parameter | Type | Description |
---|---|---|
PostComment | model | Post comments API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch post comments |
Recommended Posts API Endpoint 🟢
API endpoint for retrieving recommended posts.
Parameter | Type | Description |
---|---|---|
PostDetail | model | Recommended posts API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch recommended posts |
Search Posts API Endpoint 🟢
API endpoint for retrieving search results for posts.
Parameter | Type | Description |
---|---|---|
PostSearch | model | Search posts API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch search results |
User Live API Endpoint 🟢
API endpoint for retrieving a user's live stream.
Parameter | Type | Description |
---|---|---|
UserLive | model | User live API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to fetch user live streams |
Check Live Status API Endpoint 🟢
API endpoint for checking if a user is live.
Parameter | Type | Description |
---|---|---|
CheckLiveAlive | model | Check live status API model |
Return | Type | Description |
---|---|---|
_fetch_get_json | dict | Method to check live status |
Live Danmaku Initialization API Endpoint 🟢
API endpoint for initializing live chat messages (danmaku).
Parameter | Type | Description |
---|---|---|
LiveImFetch | model | Live chat initialization API model |
Return | Type | Description |
---|---|---|
payload_package | dict | Data package for live chat initialization |
💡 Note
- If no filter is needed, you can call the
crawler
API directly, which will return the data dictionary.