import requests import re import os import json import time from urllib.parse import unquote COOKIE_FILE = r"C:\Users\Administrator\Desktop\TikTokDownload-main\douyin_cookie.txt" def get_or_load_cookie(): """Get cookie from file or prompt user""" if os.path.exists(COOKIE_FILE): with open(COOKIE_FILE, 'r', encoding='utf-8') as f: cookie = f.read().strip() if cookie: print(f"Loaded cookie from {COOKIE_FILE}") return cookie print("\n" + "="*60) print("需要Cookie才能下载抖音视频!") print("="*60) print("\n获取Cookie步骤:") print("1. 打开Chrome/Edge浏览器,访问 www.douyin.com 并登录") print("2. 按F12打开开发者工具") print("3. 点击'网络'(Network)标签") print("4. 刷新页面") print("5. 点击列表中的任意一个请求") print("6. 在右侧'请求标头'(Request Headers)中找到Cookie") print("7. 复制整个Cookie值(很长的一串)") print("\n" + "="*60) cookie = input("\n请粘贴Cookie (直接回车跳过): ").strip() if cookie: # Save cookie for future use with open(COOKIE_FILE, 'w', encoding='utf-8') as f: f.write(cookie) print(f"Cookie已保存到 {COOKIE_FILE}") return cookie return None def download_with_cookie(share_url, cookie, save_dir=r"C:\Users\Administrator\Desktop\TestDownload"): """Download using provided cookie""" os.makedirs(save_dir, exist_ok=True) session = requests.Session() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', 'Cookie': cookie, 'Referer': 'https://www.douyin.com/', 'Accept': 'application/json, text/plain, */*', } session.headers.update(headers) # Get video ID print(f"\n获取视频ID...") resp = session.get(share_url, allow_redirects=True) final_url = resp.url print(f"URL: {final_url}") match = re.search(r'/video/(\d+)', final_url) if not match: match = re.search(r'video[=/](\d{19})', final_url) if not match: print("无法提取视频ID") return False video_id = match.group(1) print(f"视频ID: {video_id}") # Try using f2 with the cookie print(f"\n使用f2下载...") import subprocess cmd = [ r"C:\Program Files\Python311\python.exe", "-m", "f2", "dy", "-M", "one", "-u", share_url, "-p", save_dir, "-k", cookie, ] result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace') print(result.stdout) if result.returncode == 0: print("\n✓ 下载完成!") return True else: print(f"\n错误: {result.stderr}") # If f2 fails, try direct method print("\n尝试直接下载...") # Get video detail API api_url = f"https://www.douyin.com/aweme/v1/web/aweme/detail/?aweme_id={video_id}&aid=6383&cookie_enabled=true" resp = session.get(api_url) print(f"API状态: {resp.status_code}") if resp.status_code == 200 and resp.text: try: data = resp.json() if 'aweme_detail' in data: aweme = data['aweme_detail'] # Get video URL video_info = aweme.get('video', {}) play_addr = video_info.get('play_addr', {}) url_list = play_addr.get('url_list', []) if url_list: video_url = url_list[0] desc = aweme.get('desc', 'video') desc = re.sub(r'[\\/:*?"<>|]', '_', desc)[:50] print(f"\n下载视频...") video_resp = session.get(video_url) if video_resp.status_code == 200 and len(video_resp.content) > 50000: filename = f"{desc}_{video_id}.mp4" filepath = os.path.join(save_dir, filename) with open(filepath, 'wb') as f: f.write(video_resp.content) print(f"\n✓ 下载成功!") print(f" 文件: {filepath}") print(f" 大小: {len(video_resp.content) / 1024 / 1024:.2f} MB") return True except Exception as e: print(f"解析错误: {e}") return False def download_douyin_video(share_url, save_dir=r"C:\Users\Administrator\Desktop\TestDownload"): """Main download function""" cookie = get_or_load_cookie() if cookie: return download_with_cookie(share_url, cookie, save_dir) else: print("\n未提供Cookie,尝试无Cookie下载...") print("(可能无法成功)\n") # Try without cookie as last resort return download_with_cookie(share_url, "", save_dir) if __name__ == "__main__": url = "https://v.douyin.com/R5doyi5_cTk/" download_douyin_video(url)