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

Python调用youtube-dl搜索结果为空问题求助

问题分析与解决方案

你的代码出现search_results为空的核心原因有三个:

  • YouTube搜索页面的HTML结构已更新,原正则表达式匹配不到视频链接
  • 代码中未定义version变量,会导致逻辑分支错误
  • 直接用urlopen请求YouTube会被反爬,返回的内容并非真实搜索结果页面

另外,youtube-dl已停止维护,建议替换为功能更完善、支持最新YouTube的yt-dlp。


具体修复步骤

1. 替换依赖工具:用yt-dlp替代youtube-dl

先安装yt-dlp:

pip install yt-dlp

后续命令中把youtube-dl替换为yt-dlp即可,参数兼容大部分原有选项。

2. 修复搜索逻辑:改用yt-dlp内置的搜索功能(更可靠)

不需要自己解析HTML,yt-dlp本身支持直接搜索并获取视频链接,避免页面结构变化导致的匹配失败。

3. 修正未定义变量与请求问题

移除无效的version判断,改用更可靠的方式处理Python版本差异(yt-dlp已兼容所有Python3版本)。


完整修正后的代码

import os
import sys
from yt_dlp import YoutubeDL

def single_download(song=None):
    if not song:
        song = input('Enter the song name or youtube link: ')

    # 配置yt-dlp参数
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
        'postprocessor_args': [
            '-metadata', 'title=%(title)s',
            '-metadata', 'artist=%(artist)s'
        ],
        'embedthumbnail': True,
        'outtmpl': '%(title)s.%(ext)s',
        'quiet': False,
        'no_warnings': True,
    }

    try:
        with YoutubeDL(ydl_opts) as ydl:
            if "youtube.com/" not in song and "youtu.be/" not in song:
                # 直接搜索并下载第一个结果
                print(f'Searching for "{song}"...')
                search_results = ydl.extract_info(f"ytsearch:{song}", download=False)['entries']
                if not search_results:
                    print('No search results found')
                    return None
                # 下载第一个结果
                ydl.download([search_results[0]['webpage_url']])
                print(f'Downloaded: {search_results[0]["title"]}')
            else:
                # 处理直接链接
                info = ydl.extract_info(song, download=False)
                print(f'Downloading {info["title"]}...')
                ydl.download([song])
    except Exception as e:
        print(f'Error: {str(e)}')
        return None

if __name__ == "__main__":
    single_download()

为什么原代码失效?

  1. HTML结构变化:YouTube现在的搜索结果链接不再是简单的href="/watch?v=xxx",而是嵌套在复杂的组件中,且很多内容是JavaScript动态加载的,静态获取HTML无法拿到真实链接。
  2. 反爬机制:YouTube会检测到非浏览器请求,返回的页面内容不包含搜索结果。
  3. youtube-dl停止维护:自2021年起youtube-dl不再更新,无法适配YouTube的新接口和反爬策略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:53:12