Python youtube-dl 问题

问题描述 投票:0回答:0

我正在尝试编写一个简单的 python 脚本来使用 youtube-dl 搜索、下载和转换 youtube 视频文件。

我遇到了以下代码,它采用歌曲名称,搜索相应的 youtube 视频并将视频转换为 mp3 文件。

但是,search_results 变量返回为一个空列表 ([])。我试图更改代码中的多个内容,例如指定解码类型(utf-8 等),但仍然没有成功。

非常感谢您对此问题的帮助。如果需要任何其他信息,请随时询问。

import re
import urllib
from urllib.request import urlopen
import os
import sys

# download directly with a song name or link
def single_download(song=None):

    encode = urllib.parse.urlencode

    if not(song):
        song = input('Enter the song name or youtube link: ')  # get the song name from user

    if "youtube.com/" not in song:
        # try to get the search result and exit upon error
        try:
            query_string = encode({"search_query" : song})
            html_content = urlopen("http://www.youtube.com/results?" + query_string)

            if version == 3:  # if using python 3.x
                search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
            else:  # if using python 2.x
                search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read())
        except:
            print('Network Error')
            return None
        
        # make command that will be later executed
        command = 'youtube-dl --embed-thumbnail --no-warnings --extract-audio --audio-format mp3 -o "%(title)s.%(ext)s" ' + search_results[0]
        
    else:      # For a link
        # make command that will be later executed
        command = 'youtube-dl --embed-thumbnail --no-warnings --extract-audio --audio-format mp3 -o "%(title)s.%(ext)s" ' + song[song.find("=")+1:]
        song=video_title(song)

    try:       # Try downloading song
        print('Downloading %s' % song)
        os.system(command)
    except:
        print('Error downloading %s' % song)
        return None
python python-re youtube-dl
© www.soinside.com 2019 - 2024. All rights reserved.