Beginning to Grasp the Objective
I'm now fully immersed in understanding the user's objective – a Python script for podcast management. Initially, it felt vast, but breaking it down into RSS feed retrieval and organization makes it more manageable. Parsing the feeds is next on my mind, followed by determining optimal organization strategies. I'm exploring different libraries for a streamlined workflow.
Focusing on Implementation Steps
My current focus is on the concrete steps for implementation. I'm prioritizing downloading and structuring the audio files. I've broken down the project into steps. First, locating audio links within the feed, then downloading the files. I'm currently thinking of using requests for HTTP and pathlib to structure the downloads. I also have to consider sanitizing filenames during the saving process. I feel the need to handle duplicate downloads.
Constructing the Script's Framework
I'm now concretizing the script's core structure. Imports are in place: os, feedparser, requests, and pathlib. I've outlined configuration variables for saving locations and feed lists. A vital helper function, clean_filename, uses regex to sanitize filenames. The main function will process the RSS feed, create directories, and loop through episode entries, checking for existing files before initiating downloads. The execution block sets things in motion.
Developing Download Strategy
I'm now refining the download logic, aiming for memory efficiency, especially when dealing with large MP3 files. Chunked downloads are crucial to avoid loading entire audio files into RAM. I'm exploring adding a progress bar, though simple print statements may suffice for now. I've also implemented feed parsing and episode looping, now looking for enclosures to capture the audio file URLs. My initial implementation relied on 'audio/mpeg' type identification for audio links, but now I'm looking at how the enclosures attribute works. This is part of the implementation's polish phase.
Polishing the Download Process
I've been improving the download process with considerations for robustness and user experience. To avoid excessively long downloads, I've incorporated a limit parameter to restrict the number of episodes. For reliability, I've added try/except blocks to handle potential network interruptions gracefully. I'm also ensuring file explorers sort episodes chronologically by assigning the modification time to the publication date. I'm now looking at the final code structure and documentation.
Deciding Progress Indicators
I'm now contemplating whether to integrate tqdm for a progress bar. Adding dependencies increases complexity; therefore, I'll stick with straightforward print statements. This keeps the code simple and easy to copy-paste. I'll note tqdm as an optional upgrade in the documentation. Focusing on simplicity and copy-paste ease is more important.
This is a practical automation task. To do this robustly, we will use two external libraries:
feedparser: To easily read the podcast RSS feeds.
requests: To download the audio files.
Prerequisites
You will need to install the necessary libraries via your terminal:
pip install feedparser requests
The Python Script
Save this code as podcast_downloader.py.
import os
import re
import requests
import feedparser
import time
from pathlib import Path
# --- CONFIGURATION ---
DOWNLOAD_DIR = "Downloads/Podcasts" # Where to save the files
MAX_EPISODES = 5 # Set to None to download ALL episodes
# Add your RSS feed URLs here
RSS_FEEDS = [
"https://feeds.npr.org/510289/podcast.xml", # Planet Money
"https://feeds.99percentinvisible.org/99percentinvisible", # 99% Invisible
]
# ---------------------
def sanitize_filename(filename):
"""Removes illegal characters from filenames."""
return re.sub(r'[\\/*?:"<>|]', "", filename)
def download_file(url, filepath):
"""Downloads a file with a simple progress indicator."""
try:
response = requests.get(url, stream=True, timeout=10)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
with open(filepath, 'wb') as f:
print(f"Downloading: {os.path.basename(filepath)}")
if total_size == 0:
f.write(response.content)
else:
dl = 0
for data in response.iter_content(chunk_size=4096):
dl += len(data)
f.write(data)
# Optional: Print progress percentage (can be spammy in console)
# done = int(50 * dl / total_size)
# sys.stdout.write(f"\r[{'=' * done}{' ' * (50-done)}] {dl//1024} KB")
# sys.stdout.flush()
print(f" -> Completed: {os.path.basename(filepath)}")
return True
except Exception as e:
print(f"XX Error downloading {url}: {e}")
# Remove partial file if failed
if os.path.exists(filepath):
os.remove(filepath)
return False
def process_feed(rss_url):
print(f"\nParsed Feed: {rss_url}...")
feed = feedparser.parse(rss_url)
if feed.bozo:
print(f"XX Error parsing feed: {feed.bozo_exception}")
return
podcast_title = sanitize_filename(feed.feed.title)
# Create directory structure: Downloads/Podcasts/Podcast Name
podcast_dir = Path(DOWNLOAD_DIR) / podcast_title
podcast_dir.mkdir(parents=True, exist_ok=True)
print(f"--- {podcast_title} ---")
count = 0
for entry in feed.entries:
if MAX_EPISODES and count >= MAX_EPISODES:
break
# Find the audio link (enclosure)
audio_url = None
for link in entry.get("links", []):
if link.get("type", "").startswith("audio"):
audio_url = link.get("href")
break
if not audio_url:
# Fallback: check for enclosures attribute directly
for enclosure in entry.get("enclosures", []):
if enclosure.get("type", "").startswith("audio"):
audio_url = enclosure.get("href")
break
if audio_url:
episode_title = sanitize_filename(entry.title)
# Guess extension from URL or default to .mp3
ext = ".mp3"
if ".m4a" in audio_url: ext = ".m4a"
filename = f"{episode_title}{ext}"
filepath = podcast_dir / filename
# Check if file already exists (skip if yes)
if filepath.exists():
print(f"Skipping (Already exists): {filename}")
else:
success = download_file(audio_url, filepath)
if success:
# Optionally set file modification time to pubDate
# (Requires complex date parsing, skipped here for simplicity)
pass
# Be polite to the server
time.sleep(1)
count += 1
else:
print(f"Skipping {entry.title}: No audio source found.")
def main():
start_time = time.time()
# Ensure base directory exists
Path(DOWNLOAD_DIR).mkdir(parents=True, exist_ok=True)
for rss in RSS_FEEDS:
process_feed(rss)
print(f"\nAll done! Time taken: {time.time() - start_time:.2f} seconds.")
if __name__ == "__main__":
main()
How it works
- Organization: It creates a folder for every podcast feed (using the Podcast Title from the RSS) inside a
Downloads folder.
- Sanitization: It uses
re.sub to strip characters like ?, :, or / from episode titles so they can be valid filenames on Windows, Mac, and Linux.
- Skip Logic: It checks
if filepath.exists() before downloading. You can run this script daily; it will skip what you already have and only download new specific episodes.
- Enclosure Parsing: RSS feeds store audio files in "enclosures" or "links." The script iterates through them to find the one marked standard audio types.
- Streaming: It uses
requests.get(..., stream=True) and writes the file in chunks. This prevents the script from crashing your computer's memory if you are downloading a large 200MB episode.
Customization
- Where to find RSS URLs? Look for the RSS symbol on a podcast website, or search sites like ListenNotes.
- Download Everything: Change
MAX_EPISODES = 5 to MAX_EPISODES = None to download the entire history of the podcast.
- Download Location: Change
DOWNLOAD_DIR to an absolute path (e.g., C:/Users/You/Music/Podcasts or /home/you/Podcasts) if you want them stored elsewhere.