You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python检查YouTube视频是否存在于目录及实现播放列表断点续传

Hey there! Let's break down solutions to your two Python + YouTube download questions, with polished code based on your reference snippet.

问题1:检查YouTube视频是否存在于指定本地目录

To verify if a YouTube video is already saved locally, you need to:

  1. Fetch the video's official title (since pytube uses this as the default filename)
  2. Construct the full local file path using the title and your target directory
  3. Use os.path.exists() to check for the file's presence

Here's a robust implementation:

import os
from pytube import YouTube

def check_video_exists(youtube_url, local_dir):
    try:
        # Fetch video metadata to get the title
        yt = YouTube(youtube_url)
        # Pytube saves videos as [title].mp4 by default for video streams
        video_filename = f"{yt.title}.mp4"
        full_file_path = os.path.join(local_dir, video_filename)
        
        if os.path.exists(full_file_path):
            print(f"✅ Video '{yt.title}' already exists in {local_dir}")
            return True
        else:
            print(f"❌ Video '{yt.title}' not found in {local_dir}")
            return False
    except Exception as e:
        print(f"Error fetching video info: {str(e)}")
        return False

# Usage example
target_video_url = input("Enter YouTube video link: ")
target_directory = "D:\\YouTube\\Yash Raj Mukhate"
check_video_exists(target_video_url, target_directory)

Key Notes:

  • Use os.path.join() instead of hardcoding paths to avoid slash errors across operating systems
  • Added exception handling to catch issues like invalid URLs or network problems
  • Remember: If you download non-MP4 streams (e.g., audio-only), adjust the filename suffix accordingly
问题2:实现YouTube播放列表断点续传下载

Your goal is to skip already downloaded videos when resuming a playlist download. Let's fix and enhance your reference code to handle this reliably:

import os
from pytube import YouTube, Playlist
from pytube.cli import on_progress

def download_single_video(video_url, save_dir):
    try:
        yt = YouTube(video_url, on_progress_callback=on_progress)
        video_title = yt.title
        video_filename = f"{video_title}.mp4"
        full_path = os.path.join(save_dir, video_filename)
        
        # Skip if file already exists
        if os.path.exists(full_path):
            print(f"⏭️ Skipping existing video: {video_title}")
            return
        
        # Download highest resolution video
        print(f"📥 Starting download: {video_title}")
        video_stream = yt.streams.get_highest_resolution()
        video_stream.download(output_path=save_dir)
        print(f"✅ Download completed: {video_title}\n")
    except Exception as e:
        print(f"❌ Failed to download {video_url}: {str(e)}\n")

def resume_playlist_download(playlist_url, save_dir):
    # Create save directory if it doesn't exist
    os.makedirs(save_dir, exist_ok=True)
    
    try:
        playlist = Playlist(playlist_url)
        total_videos = len(playlist.video_urls)
        print(f"🎵 Playlist loaded: {total_videos} videos total\n")
        
        # Iterate through each video in the playlist
        for index, video_url in enumerate(playlist.video_urls, 1):
            print(f"Processing video {index}/{total_videos}...")
            download_single_video(video_url, save_dir)
            
    except Exception as e:
        print(f"❌ Failed to load playlist: {str(e)}")

# Run the downloader
if __name__ == "__main__":
    playlist_link = input("Enter YouTube playlist link: ")
    download_dir = "D:\\YouTube\\Yash Raj Mukhate"
    resume_playlist_download(playlist_link, download_dir)

Improvements Over Your Reference Code:

  • Fixed the path concatenation bug (your original code missed a slash between the directory and filename)
  • Added automatic directory creation with os.makedirs() to avoid "directory not found" errors
  • Encapsulated single-video logic into a reusable function for cleaner code
  • Added exception handling to prevent the entire download from crashing if one video fails
  • Included clear progress indicators so you can track where you are in the playlist
  • Uses os.path.join() for cross-platform path compatibility

内容的提问来源于stack exchange,提问作者Laxmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 14:27:33