#!/usr/bin/env python3
"""
YouTube Video URL Fetcher
This script allows the user to input a search query and retrieves a list of YouTube video URLs
corresponding to that query using the `yt-dlp` module.
The script is designed with adherence to PEP-8 standards, includes type hints for clarity,
and implements comprehensive error handling for robustness.
"""
from typing import List
import sys
from yt_dlp import YoutubeDL
from yt_dlp.utils import DownloadError
def fetch_youtube_video_urls(query: str, max_results: int = 10) -> List[str]:
"""
Fetches a list of YouTube video URLs based on the search query.
Args:
query: The search query string.
max_results: The maximum number of video URLs to return.
Returns:
A list of YouTube video URLs.
Raises:
ValueError: If the query is empty or None.
RuntimeError: If there is an error fetching video URLs.
"""
if not query:
raise ValueError("The search query must not be empty.")
ydl_opts = {
'default_search': 'ytsearch',
'quiet': True,
'extract_flat': True,
'skip_download': True,
'noplaylist': True,
}
try:
with YoutubeDL(ydl_opts) as ydl:
search_results = ydl.extract_info(f"ytsearch{max_results}:{query}", download=False)
videos = search_results.get('entries', [])
video_urls = [f"https://www.youtube.com/watch?v={video['id']}" for video in videos if video.get('id')]
return video_urls
except DownloadError as e:
raise RuntimeError(f"An error occurred while fetching video URLs: {e}") from e
def main() -> None:
"""Main function to execute the script."""
try:
query = input("Enter your YouTube search query: ").strip()
video_urls = fetch_youtube_video_urls(query)
if video_urls:
print("\nFound YouTube Video URLs:")
for url in video_urls:
print(url)
else:
print("No videos found for the given query.")
except ValueError as ve:
print(f"Input Error: {ve}", file=sys.stderr)
except RuntimeError as re:
print(f"Runtime Error: {re}", file=sys.stderr)
except KeyboardInterrupt:
print("\nOperation cancelled by the user.", file=sys.stderr)
except Exception as e:
print(f"An unexpected error occurred: {e}", file=sys.stderr)
if __name__ == "__main__":
main()
Instructions
-
Install yt-dlp Module:
Ensure that you have the yt-dlp module installed. You can install it using pip:
pip install yt-dlp
-
Run the Script:
Save the script to a file, for example, youtube_fetcher.py, and run it:
python youtube_fetcher.py
-
Enter Search Query:
When prompted, enter your YouTube search query:
Enter your YouTube search query: relaxing music
-
View Results:
The script will output a list of YouTube video URLs matching your query:
Found YouTube Video URLs:
https://www.youtube.com/watch?v=dQw4w9WgXcQ
https://www.youtube.com/watch?v=5qap5aO4i9A
...
Features
- PEP-8 Compliance: The code follows PEP-8 style guidelines for readability and maintainability.
- Type Hints: Uses the
typing module for type annotations, enhancing code clarity.
- Robustness: Includes comprehensive error handling to manage exceptions gracefully.
- Scalability: Designed to handle large datasets and can be modified to fetch more results by adjusting
max_results.
- Modularity: The
fetch_youtube_video_urls function can be imported and used in other modules or scripts.
Error Handling
- ValueError: Raised if the search query is empty.
- RuntimeError: Captures errors during the fetching of video URLs.
- KeyboardInterrupt: Handles user cancellation gracefully.
- Exception: Catches any unexpected errors.
Customization
-
max_results Parameter: By default, the script fetches up to 10 video URLs. You can adjust this number by changing the max_results parameter in the fetch_youtube_video_urls function call.
video_urls = fetch_youtube_video_urls(query, max_results=20)
Dependencies
Please ensure you comply with YouTube's Terms of Service when accessing and using video URLs.