|
import os |
|
import json |
|
import re |
|
import yt_dlp |
|
import argparse |
|
|
|
# Function to recursively extract TikTok video links |
|
def extract_tiktok_links(data): |
|
links = [] |
|
if isinstance(data, dict): |
|
for key, value in data.items(): |
|
links.extend(extract_tiktok_links(value)) |
|
elif isinstance(data, list): |
|
for item in data: |
|
links.extend(extract_tiktok_links(item)) |
|
elif isinstance(data, str): |
|
if re.match(r'https://www\.tiktokv\.com/share/video/\d+', data): |
|
links.append(data) |
|
return links |
|
|
|
# Function to download videos using yt-dlp |
|
def download_video_with_ytdlp(url, output_folder): |
|
ydl_opts = { |
|
'outtmpl': os.path.join(output_folder, '%(id)s.%(ext)s'), # Save with video ID as the filename |
|
'format': 'mp4', # Ensure videos are saved as .mp4 |
|
'quiet': False, # Show download progress |
|
} |
|
try: |
|
with yt_dlp.YoutubeDL(ydl_opts) as ydl: |
|
ydl.download([url]) |
|
print(f"Downloaded: {url}") |
|
except Exception as e: |
|
print(f"Failed to download {url}: {str(e)}") |
|
|
|
# Function to handle command-line arguments |
|
def parse_arguments(): |
|
parser = argparse.ArgumentParser(description="Download TikTok videos from a JSON file containing links.") |
|
parser.add_argument("input_file", type=str, help="Path to the JSON file containing TikTok video links") |
|
parser.add_argument("output_folder", type=str, help="Directory where downloaded videos will be saved") |
|
return parser.parse_args() |
|
|
|
# Main script |
|
def main(): |
|
args = parse_arguments() |
|
|
|
# Create the output folder if it doesn't exist |
|
os.makedirs(args.output_folder, exist_ok=True) |
|
|
|
# Load the JSON data |
|
with open(args.input_file, 'r', encoding='utf-8') as f: |
|
data = json.load(f) |
|
|
|
# Extract video links from the JSON data |
|
video_links = extract_tiktok_links(data) |
|
print(f"Found {len(video_links)} video links.") |
|
|
|
# Download each video |
|
for link in video_links: |
|
download_video_with_ytdlp(link, args.output_folder) |
|
|
|
print(f"All videos have been processed. Check the '{args.output_folder}' folder.") |
|
|
|
if __name__ == "__main__": |
|
main() |