Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK :using python module , user input query output list of urls of youtube video (write in .txt all list )
youtube-dl
yt-dlp
Assistant
Here is a Python script that takes a user input query, searches for YouTube videos matching the query using the yt-dlp module, outputs a list of video URLs, and writes them to a text file.
python
import sys
from typing import List
from yt_dlp import YoutubeDL
def get_video_urls(query: str, max_results: int = 10) -> List[str]:
"""
Retrieves video URLs from YouTube based on the search query.
Args:
query (str): The search query string.
max_results (int, optional): Maximum number of results to retrieve. Defaults to 10.
Returns:
List[str]: A list of video URLs.
"""
ydl_opts = {
'quiet': True,
'extract_flat': 'in_playlist',
'skip_download': True,
}
try:
with YoutubeDL(ydl_opts) as ydl:
search_query = f"ytsearch{max_results}:{query}"
info = ydl.extract_info(search_query, download=False)
video_entries = info.get('entries', [])
video_urls = [
f"https://www.youtube.com/watch?v={entry['id']}"
for entry in video_entries if 'id' in entry
]
return video_urls
except Exception as error:
print(f"An error occurred while fetching video URLs: {error}", file=sys.stderr)
return []
def write_urls_to_file(urls: List[str], filename: str) -> None:
"""
Writes a list of URLs to a text file.
Args:
urls (List[str]): The list of URLs to write.
filename (str): The filename to write the URLs to.
"""
try:
with open(filename, 'w', encoding='utf-8') as file:
for url in urls:
file.write(f"{url}\n")
except Exception as error:
print(f"An error occurred while writing to file '{filename}': {error}", file=sys.stderr)
def main() -> None:
"""
Main function to execute the script logic.
"""
try:
query = input("Enter your search query: ").strip()
if not query:
print("No search query provided.", file=sys.stderr)
sys.exit(1)
urls = get_video_urls(query)
if urls:
print("\nVideo URLs:")
for url in urls:
print(url)
output_filename = 'video_urls.txt'
write_urls_to_file(urls, output_filename)
print(f"\nVideo URLs have been written to '{output_filename}'.")
else:
print("No video URLs found.", file=sys.stderr)
except KeyboardInterrupt:
print("\nOperation canceled by user.", file=sys.stderr)
sys.exit(1)
except Exception as error:
print(f"An unexpected error occurred: {error}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
Requirements:
Python 3.6+
yt-dlp module: Install using pip:
bash
pip install yt-dlp
Explanation:
get_video_urls: This function takes a search query and returns a list of YouTube video URLs. It utilizes yt_dlp to perform a YouTube search and extracts video IDs to construct full URLs.
Uses yt_dlp.YoutubeDL with options:
'quiet': True to suppress console output from yt_dlp.
'extract_flat': 'in_playlist' to prevent extracting all video metadata, improving performance.
'skip_download': True to avoid downloading any video content.
Constructs the search query with ytsearch and the maximum results desired.
Extracts video entries and builds full YouTube URLs.
Includes exception handling to catch errors during the extraction process.
write_urls_to_file: Writes the list of URLs to a specified text file.
Opens the file with UTF-8 encoding.
Writes each URL on a new line.
Handles exceptions that may occur during file operations.
main: Orchestrates the script's execution.
Prompts the user for a search query.
Validates the input and exits if it's empty.
Calls get_video_urls to retrieve the URLs.
Displays the URLs to the console.
Writes the URLs to video_urls.txt.
Handles keyboard interrupt (Ctrl+C) gracefully.
Catches any unexpected exceptions.
Usage:
Run the script:
Save the script to a file, for example, youtube_search.py, and run:
bash
python youtube_search.py
Enter your search query when prompted:
code
Enter your search query: funny cat videos
Output:
The script will display the retrieved video URLs.
It will also write all URLs to video_urls.txt in the same directory.
code
Video URLs:
https://www.youtube.com/watch?v=abc123...
https://www.youtube.com/watch?v=def456...
...
Video URLs have been written to 'video_urls.txt'.
Notes:
Adjusting Results: By default, the script retrieves up to 10 video URLs. You can change the max_results parameter in the get_video_urls function call to retrieve more or fewer results.
python
urls = get_video_urls(query, max_results=20)
Error Handling: The script includes comprehensive error handling to manage unexpected situations like network errors or interrupted execution.
Code Style: The script adheres to PEP-8 standards for code style and readability, including proper naming conventions, spacing, and comments.
Type Hints: Utilizes Python's typing module for type hinting, improving code clarity and maintainability.
Dependencies:
Ensure you have yt-dlp installed. If not, install it using pip as shown above.
The script requires an active internet connection to fetch data from YouTube.