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

Python播客下载脚本:for循环中continue跳过迭代失效问题

问题分析与修复方案

核心问题

你的脚本重复下载已存在剧集的主要原因是链接匹配逻辑错误:

  • 写入日志时给链接加了换行符(link1 + '\n'),但检查时用原始link1去匹配包含换行符的日志内容,导致明明已存在的链接被判定为不存在,触发重复下载。
  • 每次启动脚本都会向日志追加写入标题行,造成日志冗余,同时可能干扰匹配逻辑。
  • 文件句柄未正确管理,存在资源泄漏风险,且写入内容可能未及时刷新到磁盘。

修复后的代码

import feedparser
import requests
from pathlib import Path

# 获取用户输入并转换类型
pod_link = input("rss feed link : ")
max_loop = int(input("The maximum number of podcasts to download : "))

# 解析RSS源
print("parsing the rss file...")
feed = feedparser.parse(pod_link)

# 校验RSS源有效性
if not feed['feed']:
    raise RuntimeError("无效的RSS源,请检查链接")

# 初始化计数器
download_count = 0
log_path = Path("pod_list.lst")

# 初始化日志文件(仅当文件不存在时写入标题)
if not log_path.exists():
    with open(log_path, 'w', encoding='utf-8') as f:
        f.write("list of all podcasts links\n")

# 读取已下载的链接集合(去除换行符,提升匹配效率)
with open(log_path, 'r', encoding='utf-8') as f:
    # 跳过标题行,读取所有链接并去除换行符
    downloaded_links = {line.strip() for line in f if line.strip() and not line.startswith("list of all")}

# 遍历剧集开始处理
for entry in feed.entries:
    if download_count >= max_loop:
        break
    
    link = entry.links[0]
    pod_title = entry.title
    link1 = link["href"]

    # 检查是否已下载
    if link1 in downloaded_links:
        print(f"跳过已下载的剧集:{pod_title}")
        continue
    
    # 下载并记录
    print(f"正在下载剧集 {download_count + 1}:{pod_title}")
    # 下载音频
    try:
        podcast = requests.get(link1)
        podcast.raise_for_status()  # 捕获请求错误
        # 处理标题中的非法字符,避免创建文件失败
        safe_title = "".join(c for c in pod_title if c not in r'\/:*?"<>|')
        with open(f"{safe_title}.mp3", 'wb') as f:
            f.write(podcast.content)
    except Exception as e:
        print(f"下载 {pod_title} 失败:{str(e)}")
        continue
    
    # 更新日志和已下载集合
    with open(log_path, 'a', encoding='utf-8') as f:
        f.write(f"{link1}\n")
    downloaded_links.add(link1)
    download_count += 1

print("任务完成")

关键修改点

  • 链接匹配优化:用集合存储已下载链接(去除换行符),匹配更准确且效率更高。
  • 日志初始化逻辑:仅在日志文件不存在时写入标题,避免冗余内容。
  • 文件安全处理:使用Path判断文件存在性,用with语句自动管理文件句柄,避免资源泄漏。
  • 错误处理:增加requests请求错误捕获,处理标题中的非法字符,避免创建文件失败。
  • 变量命名优化:将loop改为download_count,语义更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:50:23