Certainly! Below is a Python script that allows a user to input a search query and returns a list of YouTube video URLs corresponding to that query. This script adheres to the PEP-8 standards, utilizes type hints from the typing module for clarity, and employs the yt-dlp module to perform the search and extract video URLs. Comprehensive error handling is implemented to ensure robustness.
Explanation:
Modules Used:
yt_dlp: A powerful downloader that supports YouTube and many other platforms. It is used here to perform the YouTube search and extract video information.
typing: Provides type hints for better code clarity and maintainability.
sys: Allows interaction with the interpreter, used here to handle exiting gracefully on critical errors.
Functionality:
The script defines a search_youtube function that takes a search query and the desired number of video URLs to retrieve.
It configures yt_dlp with search parameters and extracts video URLs from the search results.
Comprehensive error handling ensures that any issues during the search or extraction process are caught and reported with meaningful messages.
Usage:
When run, the script prompts the user to enter a search query and the number of video URLs they wish to retrieve.
It then displays the list of retrieved YouTube video URLs.
Best Practices:
The code strictly follows PEP-8 standards for readability and structure.
Type hints enhance code clarity and assist with maintainability.
The script is optimized for efficiency and can handle varying sizes of search results gracefully.
Prerequisites:
Before running the script, ensure that yt-dlp is installed. You can install it using pip:
bash
pip install yt-dlp
Code:
python
import sys
from typing import List
from yt_dlp import YoutubeDL
from yt_dlp.utils import DownloadError
def search_youtube(query: str, max_results: int = 10) -> List[str]:
"""
Search YouTube for a given query and return a list of video URLs.
Args:
query (str): The search query.
max_results (int): Maximum number of video URLs to return.
Returns:
List[str]: A list of YouTube video URLs.
Raises:
ValueError: If the query is empty or max_results is non-positive.
RuntimeError: If the search fails due to external issues.
"""
if not query:
raise ValueError("Search query must not be empty.")
if max_results <= 0:
raise ValueError("max_results must be a positive integer.")
ydl_opts = {
'quiet': True,
'skip_download': True,
'extract_flat': 'in_playlist',
'default_search': 'ytsearch{}'.format(max_results),
'force_generic_extractor': False,
}
try:
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(query, download=False)
entries = info.get('entries', [])
video_urls = [
f"https://www.youtube.com/watch?v={entry.get('id')}"
for entry in entries if entry.get('id')
]
return video_urls
except DownloadError as de:
raise RuntimeError(f"Failed to download information: {de}") from de
except Exception as e:
raise RuntimeError(f"An unexpected error occurred: {e}") from e
def main() -> None:
"""
Main function to execute the YouTube search and print video URLs.
"""
try:
query = input("Enter YouTube search query: ").strip()
if not query:
print("Error: Search query cannot be empty.", file=sys.stderr)
sys.exit(1)
max_results_input = input("Enter the number of results to retrieve: ").strip()
if not max_results_input.isdigit():
print("Error: Number of results must be a positive integer.", file=sys.stderr)
sys.exit(1)
max_results = int(max_results_input)
if max_results <= 0:
print("Error: Number of results must be greater than zero.", file=sys.stderr)
sys.exit(1)
video_urls = search_youtube(query, max_results=max_results)
if not video_urls:
print("No videos found for the given query.")
return
print("\nYouTube Video URLs:")
for idx, url in enumerate(video_urls, start=1):
print(f"{idx}. {url}")
except ValueError as ve:
print(f"Input Error: {ve}", file=sys.stderr)
sys.exit(1)
except RuntimeError as re:
print(f"Runtime Error: {re}", file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
print("\nOperation cancelled by user.", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"An unexpected error occurred: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
Usage Example:
bash
$ python youtube_search.py
Enter YouTube search query: Python programming tutorials
Enter the number of results to retrieve: 5
YouTube Video URLs:
1. https://www.youtube.com/watch?v=rfscVS0vtbw
2. https://www.youtube.com/watch?v=H1elmMBnykA
3. https://www.youtube.com/watch?v=WGJJIrtnfpk
4. https://www.youtube.com/watch?v=_uQrJ0TkZlc
5. https://www.youtube.com/watch?v=VAcKXS_V_Dg
Notes:
Error Handling: The script gracefully handles various error scenarios, including invalid input, issues during the search process, and unexpected exceptions.
Scalability: By allowing the user to specify the number of results, the script can handle large datasets efficiently up to the specified limit.
Maintainability: Using type hints and adhering to PEP-8 standards ensures that the codebase remains maintainable and easily understandable for future developers.
Feel free to integrate this script into larger projects or modify it further to suit specific requirements.