如何让Python TikTok下载脚本读取外部txt文件实现批量下载
TikTok批量下载解决方案
两种实现方式均可,优先推荐直接修改原脚本,运行效率更高、容错性更强,也无需额外编写终端循环命令。
方案1:直接修改原Python脚本(推荐)
修改说明
保留原有单条下载能力的基础上,新增批量下载支持:
- 新增
--url-file参数传入链接txt文件路径 - 自动按序号命名输出文件,避免覆盖
- 新增异常捕获逻辑,单条链接下载失败不会中断整体任务
- 可自定义请求延迟,避免IP被封禁
修改后完整代码
from argparse import ArgumentParser import os from urllib.parse import parse_qsl, urlparse import requests import time class TikTokDownloader: HEADERS = { 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'DNT': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', 'Accept': '*/*', 'Sec-Fetch-Site': 'same-site', 'Sec-Fetch-Mode': 'no-cors', 'Sec-Fetch-Dest': 'video', 'Referer': 'https://www.tiktok.com/', 'Accept-Language': 'en-US,en;q=0.9,bs;q=0.8,sr;q=0.7,hr;q=0.6', 'sec-gpc': '1', 'Range': 'bytes=0-', } def __init__(self, url: str, web_id: str): self.__url = url self.__cookies = { 'tt_webid': web_id, 'tt_webid_v2': web_id } def __get_video_url(self) -> str: response = requests.get(self.__url, cookies=self.__cookies, headers=TikTokDownloader.HEADERS) return response.text.split('"playAddr":"')[1].split('"')[0].replace(r'\u0026', '&') def download(self, file_path: str): video_url = self.__get_video_url() url = urlparse(video_url) params = tuple(parse_qsl(url.query)) request = requests.Request(method='GET', url='{}://{}{}'.format(url.scheme, url.netloc, url.path), cookies=self.__cookies, headers=TikTokDownloader.HEADERS, params=params) prepared_request = request.prepare() session = requests.Session() response = session.send(request=prepared_request) response.raise_for_status() if os.path.exists(file_path): choice = input(f'File {file_path} already exists. Overwrite? (Y/N): ') if choice.lower() != 'y': return with open(os.path.abspath(file_path), 'wb') as output_file: output_file.write(response.content) if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('--web-id', required=True, help='Value of tt_webid or tt_webid_v2 cookie (they are the same).') parser.add_argument('-o', '--output', default='download.mp4', help='Full output path (only for single download)') parser.add_argument('--url-file', help='Path to txt file with one TikTok URL per line, for batch download') parser.add_argument('url', nargs='?', help='Single video url (https://www.tiktok.com/@username/video/1234567890123456789 or https://vm.tiktok.com/a1b2c3/).') args = parser.parse_args() # 批量下载逻辑 if args.url_file: if not os.path.exists(args.url_file): print(f"Error: File {args.url_file} not found") exit(1) # 读取所有链接,过滤空行 with open(args.url_file, 'r', encoding='utf-8') as f: url_list = [line.strip() for line in f if line.strip()] total = len(url_list) print(f"Found {total} links to download") # 循环下载 for idx, url in enumerate(url_list, start=1): try: print(f"Processing {idx}/{total}: {url}") output_path = f"./tiktok_video_{idx}.mp4" downloader = TikTokDownloader(url, args.web_id) downloader.download(output_path) print(f"Successfully saved to {output_path}") # 取消下方注释添加下载间隔,单位为秒,避免被封IP # time.sleep(2) except Exception as e: print(f"Download failed for {url}: {str(e)}") continue # 原有单条下载逻辑 else: if not args.url: print("Error: Please provide either a single URL or --url-file parameter for batch download") parser.print_help() exit(1) downloader = TikTokDownloader(args.url, args.web_id) downloader.download(args.output)
使用方法
批量下载直接执行以下命令即可:
python3 ./tiktok.py --web-id 你自己的tt_webid值 --url-file ./links.txt
所有文件会自动按tiktok_video_1.mp4、tiktok_video_2.mp4的命名规则保存在当前目录。
方案2:Shell循环实现(无需修改脚本,适合临时使用)
如果不想改动原脚本,可以直接在Linux/Mac终端或者Windows WSL中执行循环命令逐一下载:
# 替换为你自己的tt_webid值 WEB_ID="1234567890123" # 计数变量,用于命名文件 COUNT=1 # 逐行读取links.txt的链接下载 while read -r URL; do if [ -n "$URL" ]; then python3 ./tiktok.py --web-id "$WEB_ID" -o "./download_${COUNT}.mp4" "$URL" COUNT=$((COUNT+1)) # 可选添加延迟,防止被封 sleep 2 fi done < links.txt
该方案的缺点是每次下载都会重新启动Python进程,1000条链接的运行开销比修改脚本更高,也不支持异常跳过、断点续传等功能。
注意事项
- tt_webid可以从浏览器TikTok页面的Cookie中获取,tt_webid和tt_webid_v2的值通用
- 建议添加2-3秒的下载间隔,避免请求频率过高触发TikTok的反爬机制
- 如果需要自定义输出文件名规则,可以直接修改脚本中
output_path的拼接逻辑
内容的提问来源于stack exchange,提问作者Ivy Knm
相关产品推荐
相关产品推荐

