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

使用Pytube下载YouTube播放列表音频时阿拉伯语命名报错求助

解决Pytube下载含阿拉伯语标题播放列表的OSError问题

问题原因

Windows系统下文件名禁止包含<>:"/\|?*这些特殊字符,你的代码直接使用视频标题作为文件名,当标题包含|这类非法字符时,就会触发OSError: [Errno 22] Invalid argument错误(阿拉伯语标题本身不存在编码问题,特殊字符是触发错误的核心原因)。

解决方案

通过清理文件名中的非法字符,确保生成的文件名符合系统规范,同时优化错误处理逻辑:

修改后的完整代码

from pytube import Playlist
import tkinter.filedialog as filedialog

def clean_filename(filename):
    # 定义Windows系统非法文件名字符集合
    invalid_chars = '<>:"/\\|?*'
    for char in invalid_chars:
        filename = filename.replace(char, '_')
    return filename

def AudioPlaylist(url):
    i = 1
    try:
        playlist = Playlist(url)
        print(playlist.title)
    except Exception as e:
        print(f"连接错误: {e}")
        return
    folder_name = filedialog.askdirectory()
    if not folder_name:
        print("未选择目标文件夹,操作终止")
        return
    for video in playlist.videos:
        name = str(video.title)
        cleaned_name = clean_filename(name)
        audio = video.streams.get_audio_only()
        audio.download(output_path=folder_name, filename=f"{i}-{cleaned_name}.mp3")
        i += 1

关键修改点

  • 清理非法字符:clean_filename函数将所有Windows不允许的文件名字符替换为下划线,彻底避免文件名格式错误。
  • 优化错误处理:捕获具体异常并打印信息,用return替代exit(),避免直接终止整个程序。
  • 增加边界判断:处理用户取消选择文件夹的情况,防止后续代码执行报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:20:28