我正在编写一个脚本来从网上下载mp3歌曲。首先,我将在youtube上刮。如果找到,请使用youtube-dl下载并将其转换为mp3。如果没有找到(使用os.path.isfile
完成),请在beemp3(对于此示例)或mp3skulls等中废弃。仅针对ytdownload和文件检查的脚本如下:
from bs4 import BeautifulSoup
from urllib.request import urlopen,Request,urlretrieve
import re
import youtube_dl
import sys
import os
def ytscrape(searchurl,baseurl):
"""normal scraping"""
req = Request(searchurl, headers={'User-Agent':'Mozilla/5.0'})
lst[:] = []
url = urlopen(req)
soup = BeautifulSoup(url, 'lxml')
for i in soup.find_all('div',{'class':['yt-lockup-content','yt-lockup-meta-info']},limit=10):
for link,views in zip(i.select('h3 > a'),i.select('ul > li')):
if views is not None and views.next_sibling is not None:
lst.append([baseurl+link.get('href'),views.next_sibling.text])
for i in lst:
i[1] = int(re.sub(r' views|,','',i[1]))
lst.sort(key = lambda x:x[1])
url.close()
return lst[-1][0]
def dl_frm_youtube(yt_lnk,dlpath):
"""passes the youtube url of the song. it extracts audio alone and saves it
in local.
yt_lnk : youtube url for song which is priortised based on channel/views.
"""
ydl_opts = {'format':'bestaudio/best','outtmpl':dlpath+'\\%(title)s.%(ext)s','postprocessors':[{'key':'FFmpegExtractAudio','preferredcodec':'mp3','preferredquality':'192',}]}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([yt_lnk])
if os.path.isfile(dlpath+'\\%(title)s.%(ext)s'):
print('found')
else:
print('not found')
def main():
song = 'numb'
artist = 'linkin park'
baseurl = 'https://www.youtube.com'
if sys.platform == 'win32':
dlpath = os.path.join(os.environ['USERPROFILE'],'Music','spd')
if not os.path.exists(dlpath):
os.mkdir(dlpath)
else:
dlpath = '~/Music/' + song + '.mp3'
searchurl = baseurl + '/results?search_query=' + '+' + artist.replace(chr(32),'+') + '+' + song.replace(chr(32),'+')
dl_frm_youtube(ytscrape(searchurl,baseurl),dlpath)
lst = []
main()
当我尝试进行文件检查时,虽然下载的歌曲存在于路径中,但它失败了。因为它失败了,它进入了下一个功能并下载了它,导致我在我的路径中有2首歌曲。
所以,我的问题是如何设置该文件检查,以便它在dlpath中出现时应该打印 found 。
TIA
修改 根据phihag评论,我删除了所有无用的信息,更改了代码以仅包含问题部分并硬编码输入。
答案 0 :(得分:2)
最后,我找到了原因。似乎%(title)s.%(ext)s
似乎只在ydl_opts dict中保存了值。 this answer帮助了我。
我将dl_frm_youtube中的代码更改为:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
#ydl.download([yt_lnk])
info = ydl.extract_info(yt_lnk, download=True)
songname = info.get('title', None)
#print(songname)
if os.path.isfile(dlpath+'\\'+songname+'.mp3'):
print('found')
它完美无缺。如果有人发现它有用,请回答它。