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

如何在Python 3.5中验证YouTube视频URL的有效性?

Validating YouTube Video URLs in Python 3.5

Hey there! I get that you're building a video downloader with Python 3.5 and need to check if user-provided YouTube links are valid. Let's go over two reliable approaches—one lightweight and offline, another more thorough that verifies the video actually exists.

Approach 1: Regular Expression Matching (Offline, Fast)

This method checks if the URL matches known YouTube patterns without needing an internet connection. It's great for quick initial validation to catch obvious invalid links right away.

Here's a regex that covers most common YouTube URL formats:

  • Standard links like https://www.youtube.com/watch?v=abc123
  • Shortened links like https://youtu.be/abc123
  • Links with extra parameters (like &t=10s for timestamps) or embedded player URLs

Code Example:

import re

def is_valid_youtube_url(url):
    # Regex pattern to match all common YouTube URL variants
    youtube_regex = r'(https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})'
    match = re.match(youtube_regex, url)
    return bool(match)

# Test the function with sample URLs
test_urls = [
    "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "https://youtu.be/dQw4w9WgXcQ",
    "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ",
    "https://youtube.com/watch?v=dQw4w9WgXcQ&t=30s",
    "invalid-link.com",
    "https://youtube.com/watch?v=shortID"  # Too short video ID
]

for url in test_urls:
    print(f"{url}: {'Valid' if is_valid_youtube_url(url) else 'Invalid'}")

Notes:

  • The regex focuses on the 11-character YouTube video ID—this is the unique, mandatory part of every valid video link.
  • This won't confirm if the video is actually accessible (e.g., deleted, private), but it efficiently filters out non-YouTube links and malformed inputs.

Approach 2: HTTP Request Validation (Online, Thorough)

If you need to make sure the video exists and is accessible (not deleted, not private), send a lightweight HTTP HEAD request to YouTube. This avoids downloading the entire page content, making it much faster than a full GET request.

First, install a version of requests compatible with Python 3.5 (newer versions drop 3.5 support):

pip install requests<2.28

Code Example:

import requests
from re import match as re_match

def is_valid_youtube_url(url):
    youtube_regex = r'(https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})'
    return bool(re_match(youtube_regex, url))

def is_youtube_video_accessible(url, timeout=5):
    # First filter non-YouTube URLs with regex
    if not is_valid_youtube_url(url):
        return False
    
    # Convert shortened youtu.be links to standard format for consistency
    if 'youtu.be' in url:
        video_id = url.split('/')[-1].split('?')[0]
        url = f"https://www.youtube.com/watch?v={video_id}"
    
    try:
        # Send HEAD request (only fetches headers, no page content)
        response = requests.head(url, timeout=timeout, allow_redirects=True)
        
        # 200 = video exists and is public; 404 = video deleted/never existed
        if response.status_code == 200:
            return True
        elif response.status_code == 404:
            return False
        else:
            # Handle cases like 403 (private video) or 429 (rate limit)
            return False
    except requests.exceptions.RequestException:
        # Catch network errors, timeouts, or DNS issues
        return False

# Test the function
print(is_youtube_video_accessible("https://www.youtube.com/watch?v=dQw4w9WgXcQ"))  # Returns True
print(is_youtube_video_accessible("https://www.youtube.com/watch?v=invalidID123"))  # Returns False

Notes:

  • This method confirms the video is reachable. For private videos, you'll get a 403 status code—you can add logic to inform the user the video is restricted.
  • Always wrap requests in try/except blocks to handle network issues gracefully and avoid crashing your app.

Which Approach to Choose?

  • Use regex matching for quick, offline validation to filter out garbage input before making network calls.
  • Use HTTP validation if you need to ensure the video is actually available for download.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:52:31