# **Python Youtube Music Downloader** ###### tags: `crawler` [Code Link](https://github.com/t2o0n321/YoutubeDownloader) --- <h3> <strong>プロローグ</strong> </h3> > 在網路上有許多關於YouTube下載的資源,其中不免參雜了些惡意的代碼。就算找到正常的資源也不一定會完全符合自己的需求。於是才促使我寫了一個專屬自己的下載器。 <h3> <strong>About Web Crawler</strong> </h3> > 既然要做個下載器,那麼[爬蟲](https://zh.wikipedia.org/wiki/%E7%B6%B2%E8%B7%AF%E7%88%AC%E8%9F%B2)的基本觀念也是非常重要的。 > 爬蟲被業界廣泛使用,因此已經有許多前輩們替咱們寫出了各式各樣的API與函式庫,我們只需要借用前人的努力便可完成複雜的作業。爬蟲屬於比較前端的技術,因此撰寫語言以Python居多。 <h3> <strong>Let's get start</strong> </h3> > 這次使用python實作 > 使用到的API有[pytube](https://pytube.io/en/latest/) , [youtube-dl](https://github.com/ytdl-org/youtube-dl) , [pydub](https://github.com/jiaaro/pydub) **以下為這個程式的執行步驟 :** ``` 1. 獲取目標url 2. 分析url 3. 爬取資源 4. 轉檔成自己要的檔案格式 ``` 首先請求url ``` url=input('Youtube url > ') ``` 分析url ``` class urlParser: def parser(self,url): if 'youtube' not in url: print('Invalid url') return if 'playlist' in url: for video_url in Playlist(url).video_urls: a=dataDownload() a.GetAudio(video_url) return else: a=dataDownload() a.GetAudio(url) return ``` 爬取資源 ``` def GetTitle(url): with youtube_dl.YoutubeDL() as ydl: info_dict = ydl.extract_info(url,download=False) _title_=str(info_dict['title']) if '/' in _title_: portion=_title_.split('/') titleWithoutSlash='' for i in portion : titleWithoutSlash+=i return titleWithoutSlash return _title_ class dataDownload: # Get audio def GetAudio(self,url,f='bestaudio/best'): audioSavePath = os.path.dirname(__file__) + '\\music\\'+GetTitle(url)+".%(ext)s" ydl_opt={ 'format' : f, 'outtmpl' : audioSavePath } with youtube_dl.YoutubeDL(ydl_opt) as ydl: ydl.download([url]) ``` 檔案格式轉換(To mp3 format) ``` import os,glob,pydub path=os.path.dirname(__file__)+'/music' def isDir(filePath): portion=os.path.splitext(filePath) if portion[1]=='': return True else: return False def get_mp3_name(file): newName=os.path.splitext(file)[0]+'_.mp3' return newName class converter: def any_to_mp3(filePath): os.chdir(filePath) for file in glob.glob('./*'): if isDir(file)==False: print('Starting to convert '+file+' to mp3 format ...') sound=pydub.AudioSegment.from_file(file) sound.export(get_mp3_name(file),format='mp3') os.remove(file) print('Done ...') else: continue ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up