@xbibzlibrary/tiktokscrap
Version:
Powerful TikTok Scraper and Downloader Library
110 lines (85 loc) • 3.28 kB
text/typescript
import BaseScraper from './base';
import { TikTokPhoto, TikTokScrapOptions, TikTokScrapResult } from '../types';
import { ValidationError, NotFoundError } from '../errors';
export class PhotoScraper extends BaseScraper {
constructor(options: TikTokScrapOptions = {}) {
super(options);
}
public async getPhotoByUrl(url: string): Promise<TikTokScrapResult<TikTokPhoto>> {
return this.executeRequest(async () => {
if (!this.validator.validateTikTokUrl(url)) {
throw new ValidationError('Invalid TikTok URL');
}
const photoId = this.extractPhotoIdFromUrl(url);
if (!photoId) {
throw new ValidationError('Could not extract photo ID from URL');
}
return this.getPhotoById(photoId);
}, `Get photo by URL: ${url}`);
}
public async getPhotoById(id: string): Promise<TikTokPhoto> {
this.validator.validateId(id);
const url = this.buildUrl('https://www.tiktok.com', `//photo/${id}`);
const response = await this.http.get(url);
if (response.status !== 200) {
throw new NotFoundError('Photo not found');
}
return this.parser.parsePhotoData(response.data);
}
public async getPhotoTrends(count: number = 20): Promise<TikTokScrapResult<TikTokPhoto[]>> {
return this.executeRequest(async () => {
if (count <= 0 || count > 100) {
throw new ValidationError('Count must be between 1 and 100');
}
const url = this.buildUrl('https://www.tiktok.com', '/api/item_list/', {
count,
id: 1,
type: 5,
secUid: '',
maxCursor: 0,
minCursor: 0,
retryType: 0,
isWeb: 1,
itemType: 2 // 2 for photos
});
const response = await this.http.get(url);
if (response.status !== 200) {
throw new NotFoundError('Could not fetch trending photos');
}
const data = response.data;
if (!data.body || !data.body.itemListData) {
return [];
}
return data.body.itemListData.map((item: any) => this.parser.parsePhotoObject(item));
}, `Get trending photos: ${count}`);
}
public async getRecommendedPhotos(photoId: string, count: number = 10): Promise<TikTokScrapResult<TikTokPhoto[]>> {
return this.executeRequest(async () => {
this.validator.validateId(photoId);
if (count <= 0 || count > 50) {
throw new ValidationError('Count must be between 1 and 50');
}
const url = this.buildUrl('https://www.tiktok.com', '/api/recommend/item_list/', {
count,
id: photoId,
type: 0,
secUid: '',
maxCursor: 0,
minCursor: 0,
retryType: 0,
isWeb: 1,
itemType: 2 // 2 for photos
});
const response = await this.http.get(url);
if (response.status !== 200) {
throw new NotFoundError('Could not fetch recommended photos');
}
const data = response.data;
if (!data.body || !data.body.itemListData) {
return [];
}
return data.body.itemListData.map((item: any) => this.parser.parsePhotoObject(item));
}, `Get recommended photos for ${photoId}: ${count}`);
}
}
export default PhotoScraper;