Skip to content

Instantly share code, notes, and snippets.

@zone559
Last active July 4, 2025 14:51
Show Gist options
  • Select an option

  • Save zone559/bbf15c05c5255257329c60f436d01fc7 to your computer and use it in GitHub Desktop.

Select an option

Save zone559/bbf15c05c5255257329c60f436d01fc7 to your computer and use it in GitHub Desktop.
import subprocess
import re
import requests
import os
from tqdm import tqdm # For progress bar
def extract_media_id(url):
"""Extract media ID from TikTok video URL."""
match = re.search(r'/video/(\d+)', url)
return match.group(1) if match else None
def get_tiktok_media_ids(username):
"""Fetch all video media IDs for a TikTok user."""
command = [
"yt-dlp",
"--flat-playlist",
"--get-url",
f"https://www.tiktok.com/@{username}"
]
try:
print("πŸ” Fetching video links...")
result = subprocess.run(command, capture_output=True, text=True, check=True)
urls = result.stdout.splitlines()
media_ids = [extract_media_id(url) for url in urls if extract_media_id(url)]
return media_ids
except subprocess.CalledProcessError as e:
print(f"❌ Error running yt-dlp: {e.stderr}")
return []
except Exception as e:
print(f"❌ An error occurred: {e}")
return []
def download_video(media_id):
"""Download TikTok video with progress bar."""
url = f"https://tikwm.com/video/media/hdplay/{media_id}.mp4"
filename = f"{media_id}.mp4"
try:
response = requests.get(url, stream=True, allow_redirects=True)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
with open(filename, 'wb') as f, tqdm(
desc=f"πŸ“₯ {media_id}",
total=total_size,
unit='B',
unit_scale=True,
unit_divisor=1024,
) as progress_bar:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
progress_bar.update(len(chunk))
print(f"βœ… Downloaded: {filename}")
except requests.RequestException as e:
print(f"❌ Failed to download {media_id}: {e}")
if os.path.exists(filename):
os.remove(filename)
if __name__ == "__main__":
# Ask for input (username or video URL)
user_input = input("Enter TikTok username (e.g., 'tatemcrae') or video URL: ").strip()
if not user_input:
print("❌ Input cannot be empty!")
exit()
# Case 1: Direct video URL provided
if "/video/" in user_input:
media_id = extract_media_id(user_input)
if media_id:
print(f"🎬 Downloading single video: {media_id}")
download_video(media_id)
else:
print("❌ Invalid TikTok video URL!")
# Case 2: Username provided
else:
username = user_input.lstrip("@") # Remove "@" if included
media_ids = get_tiktok_media_ids(username)
if not media_ids:
print("❌ No videos found. Check username or try with --cookies.")
else:
print(f"🎬 Found {len(media_ids)} videos. Downloading...")
for media_id in media_ids:
download_video(media_id)
print("✨ All downloads completed!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment