Python脚本实现YouTube视频下载:用户输入URL模式报错求助
Hey there! Let's get your interactive YouTube downloader script up and running smoothly. Since you didn't share the exact error message, I'll walk you through a complete working version of the script, plus fix the most common issues people run into when adding user interaction.
Working Interactive YouTube Downloader Script
First, let's start with a reliable script using pytube (the go-to library for this task). This one includes user input handling, URL validation, and error catching:
from pytube import YouTube import re def is_valid_youtube_url(url): # Basic regex to validate YouTube URL format youtube_pattern = r'(https?://)?(www\.)?(youtube\.com|youtu\.be)/watch\?v=[\w-]+' return re.match(youtube_pattern, url) is not None def download_youtube_video(): # Prompt user for video URL video_url = input("Please enter the YouTube video URL: ") # Validate URL first to avoid unnecessary errors if not is_valid_youtube_url(video_url): print("Oops! That's not a valid YouTube URL. Make sure it looks like https://www.youtube.com/watch?v=xxxxxx") return try: # Initialize YouTube object yt = YouTube(video_url) # Let user pick a resolution (progressive streams include both audio + video) print(f"\nAvailable download options for '{yt.title}':") for idx, stream in enumerate(yt.streams.filter(progressive=True), 1): print(f"{idx}. Resolution: {stream.resolution} | File type: {stream.mime_type.split('/')[1]}") # Get and validate user's choice while True: try: choice = int(input("\nEnter the number of your preferred option: ")) if 1 <= choice <= len(yt.streams.filter(progressive=True)): break else: print(f"Please enter a number between 1 and {len(yt.streams.filter(progressive=True))}") except ValueError: print("That's not a valid number. Try again!") selected_stream = yt.streams.filter(progressive=True)[choice-1] # Start download and notify user print(f"\nDownloading '{yt.title}' ({selected_stream.resolution})...") selected_stream.download() print("Download completed successfully! 🎉") except Exception as e: print(f"\nSomething went wrong during download: {str(e)}") if __name__ == "__main__": download_youtube_video()
Fixes for Common Errors
If you ran into specific issues, here's how to troubleshoot them:
RegexMatchError: get_throttling_function_name: could not find match
This happens when YouTube updates its anti-scraping measures, breaking pytube's regex. Fix it by upgrading pytube to the latest version:pip install --upgrade pytubeModuleNotFoundError: No module named 'pytube'
You just need to install the library first:pip install pytubeVideo unavailableerror
Double-check that the video is public (not private/restricted) and your URL is correct. Make sure it includes the fullwatch?v=segment.PermissionError: [Errno 13] Permission denied
The script doesn't have write access to your current directory. Either run it in a folder you have permissions for, or specify an output path:# Add an output path to the download method selected_stream.download(output_path="./my_downloads")
Quick Optimization Tips
- Add a loop to let users download multiple videos without restarting the script
- Handle age-restricted videos (you'll need to add authentication for that)
- Show download progress using pytube's built-in callbacks
内容的提问来源于stack exchange,提问作者k joe

