@xbibzlibrary/tiktokscrap
v1.0.1-released
Published
Powerful TikTok Scraper and Downloader Library
Downloads
79
Maintainers
Readme
🎵 TikTok Scraper & Downloader Library
✨ Features
📦 Installation
# Using npm
npm install @xbibzlibrary/tiktokscrap
# Using yarn
yarn add @xbibzlibrary/tiktokscrap
# Using pnpm
pnpm add @xbibzlibrary/tiktokscrap🚀 Quick Start
import TikTokScrap from '@xbibzlibrary/tiktokscrap';
// Initialize the library
const tiktok = new TikTokScrap();
// Get video information
const video = await tiktok.getVideoByUrl('https://www.tiktok.com/@username/video/1234567890');
if (video.success) {
console.log('📹 Video Title:', video.data.text);
console.log('👤 Author:', video.data.author.nickname);
console.log('❤️ Likes:', video.data.stats.digg);
// Download the video
await tiktok.downloadVideo(video.data, {
outputDir: './downloads',
progressCallback: (progress) => console.log(`⏬ Progress: ${progress}%`)
});
}📖 Usage
🎬 Video Operations
const result = await tiktok.getVideoByUrl('https://www.tiktok.com/@user/video/123456');
if (result.success) {
console.log('Video Data:', result.data);
// Access: id, text, author, music, stats, videoMeta, hashtags, etc.
}const result = await tiktok.getVideoById('1234567890123456789');
if (result.success) {
const video = result.data;
console.log(`Title: ${video.text}`);
console.log(`Duration: ${video.videoMeta.duration}s`);
console.log(`Views: ${video.stats.play}`);
}const trending = await tiktok.getVideoTrends(20); // Get top 20
if (trending.success) {
trending.data.forEach(video => {
console.log(`🔥 ${video.text} - ${video.stats.play} views`);
});
}const recommended = await tiktok.getRecommendedVideos('videoId', 10);
if (recommended.success) {
console.log(`Found ${recommended.data.length} recommended videos`);
}📸 Photo Operations
const result = await tiktok.getPhotoByUrl('https://www.tiktok.com/@user/photo/123456');
if (result.success) {
const photo = result.data;
console.log(`Photos in post: ${photo.covers.length}`);
photo.covers.forEach((cover, i) => {
console.log(`Photo ${i + 1}: ${cover.url}`);
});
}const photoResult = await tiktok.getPhotoByUrl('https://www.tiktok.com/@user/photo/123456');
if (photoResult.success) {
const downloaded = await tiktok.downloadPhoto(photoResult.data, {
outputDir: './photos',
filename: 'my-tiktok-photo',
progressCallback: (progress) => {
console.log(`📥 Downloading: ${progress}%`);
}
});
if (downloaded.success) {
console.log(`✅ Downloaded ${downloaded.data.length} photos!`);
}
}👤 User Operations
const user = await tiktok.getUserByUsername('@username');
if (user.success) {
const profile = user.data;
console.log(`Name: ${profile.nickname}`);
console.log(`Followers: ${profile.fans}`);
console.log(`Following: ${profile.following}`);
console.log(`Total Likes: ${profile.heart}`);
console.log(`Videos: ${profile.video}`);
}const videos = await tiktok.getUserVideos('@username', 0, 30);
if (videos.success) {
videos.data.forEach(video => {
console.log(`📹 ${video.text}`);
console.log(` ❤️ ${video.stats.digg} | 💬 ${video.stats.comment}`);
});
}const feed = await tiktok.getUserFeed({
username: '@username',
cursor: 0,
count: 20,
type: 'post' // or 'like'
});
if (feed.success) {
console.log(`Found ${feed.data.length} posts`);
}#️⃣ Hashtag Operations
const hashtag = await tiktok.getHashtagByName('#fyp');
if (hashtag.success) {
const tag = hashtag.data;
console.log(`Title: ${tag.title}`);
console.log(`Views: ${tag.viewCount}`);
console.log(`Description: ${tag.description}`);
}const videos = await tiktok.getHashtagVideos('#dance', 0, 50);
if (videos.success) {
console.log(`Found ${videos.data.length} videos with #dance`);
}const trending = await tiktok.getTrendingHashtags(10);
if (trending.success) {
trending.data.forEach((tag, i) => {
console.log(`${i + 1}. #${tag.name} - ${tag.viewCount} views`);
});
}⬇️ Download Operations
const video = await tiktok.getVideoByUrl('https://www.tiktok.com/@user/video/123');
if (video.success) {
const download = await tiktok.downloadVideo(video.data, {
outputDir: './downloads',
filename: 'my-video.mp4',
progressCallback: (progress) => {
console.log(`⏬ ${progress}%`);
}
});
if (download.success) {
console.log(`✅ Saved to: ${download.data}`);
}
}const download = await tiktok.downloadVideoByUrl(
'https://www.tiktok.com/@user/video/123',
{
outputDir: './downloads',
progressCallback: (progress) => console.log(`${progress}%`)
}
);const videos = await tiktok.getUserVideos('@username', 0, 10);
if (videos.success) {
for (const video of videos.data) {
await tiktok.downloadVideo(video, {
outputDir: './batch-downloads',
filename: `${video.id}.mp4`
});
}
}🎯 API Documentation
Constructor Options
interface TikTokScrapOptions {
timeout?: number; // Request timeout (default: 30000ms)
retries?: number; // Retry attempts (default: 3)
userAgent?: string; // Custom user agent
proxy?: { // Proxy configuration
host: string;
port: number;
auth?: {
username: string;
password: string;
};
};
headers?: Record<string, string>; // Custom headers
}
// Usage
const tiktok = new TikTokScrap({
timeout: 60000,
retries: 5,
proxy: {
host: '127.0.0.1',
port: 8080
}
});Response Structure
interface TikTokScrapResult<T> {
success: boolean; // Request success status
data?: T; // Response data (if successful)
error?: string; // Error message (if failed)
message?: string; // Status message
}Video Data Structure
interface TikTokVideo {
id: string; // Video ID
text: string; // Video caption/description
createTime: number; // Upload timestamp
author: TikTokUser; // Author information
music: { // Music information
id: string;
title: string;
author: string;
playUrl: string;
};
stats: { // Video statistics
digg: number; // Likes
share: number; // Shares
comment: number; // Comments
play: number; // Views
};
videoMeta: { // Video metadata
width: number;
height: number;
duration: number;
cover: string; // Cover image URL
};
downloadAddr: string; // Direct download URL
hashtags: Array<{}>; // Hashtags used
// ... more fields
}💡 Advanced Examples
🔄 Error Handling
try {
const video = await tiktok.getVideoByUrl('invalid-url');
if (!video.success) {
console.error('Error:', video.error);
console.error('Message:', video.message);
}
} catch (error) {
console.error('Exception:', error.message);
}🔁 Pagination
let cursor = 0;
let allVideos = [];
while (cursor < 100) {
const result = await tiktok.getUserVideos('@username', cursor, 20);
if (!result.success || result.data.length === 0) break;
allVideos.push(...result.data);
cursor += 20;
// Rate limiting
await new Promise(resolve => setTimeout(resolve, 1000));
}
console.log(`Total videos collected: ${allVideos.length}`);📊 Statistics Collection
const user = await tiktok.getUserByUsername('@username');
if (user.success) {
const videos = await tiktok.getUserVideos('@username', 0, 100);
if (videos.success) {
const totalLikes = videos.data.reduce((sum, v) => sum + v.stats.digg, 0);
const totalViews = videos.data.reduce((sum, v) => sum + v.stats.play, 0);
const avgLikes = totalLikes / videos.data.length;
console.log(`📊 Statistics for @${user.data.uniqueId}`);
console.log(`Total Videos: ${videos.data.length}`);
console.log(`Total Likes: ${totalLikes.toLocaleString()}`);
console.log(`Total Views: ${totalViews.toLocaleString()}`);
console.log(`Average Likes: ${avgLikes.toFixed(0)}`);
}
}🎯 Custom Configuration
const tiktok = new TikTokScrap({
timeout: 60000,
retries: 5,
headers: {
'Accept-Language': 'id-ID,id;q=0.9',
'Custom-Header': 'value'
}
});
// Update configuration later
tiktok.updateOptions({
timeout: 45000,
retries: 3
});
// Get current configuration
const config = tiktok.getOptions();
console.log('Current config:', config);🎨 Progress Bar Example
import cliProgress from 'cli-progress';
const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);
const video = await tiktok.getVideoByUrl('https://...');
if (video.success) {
progressBar.start(100, 0);
await tiktok.downloadVideo(video.data, {
outputDir: './downloads',
progressCallback: (progress) => {
progressBar.update(progress);
}
});
progressBar.stop();
console.log('✅ Download complete!');
}🏗️ Architecture
@xbibzlibrary/tiktokscrap
├── 🎬 Scrapers
│ ├── VideoScraper → Video content scraping
│ ├── PhotoScraper → Photo content scraping
│ ├── UserScraper → User profile & feed
│ └── HashtagScraper → Hashtag & trends
│
├── ⬇️ Downloaders
│ ├── VideoDownloader → Video file downloads
│ └── PhotoDownloader → Photo downloads
│
├── 🛠️ Utilities
│ ├── HttpClient → HTTP requests & retries
│ ├── Parser → HTML/JSON parsing
│ ├── Validator → Input validation
│ └── Logger → Logging system
│
└── 🎯 Core
├── Types → TypeScript definitions
└── Errors → Custom error classes🤝 Contributing
Contributions are welcome! Feel free to:
- 🐛 Report bugs
- 💡 Suggest new features
- 🔧 Submit pull requests
- 📖 Improve documentation
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
👨💻 Author
Xbibz Official
⚠️ Disclaimer
This library is for educational purposes only. Please respect TikTok's Terms of Service and use this library responsibly. The author is not responsible for any misuse of this library.
📊 Project Stats

