# 抓YT音樂影片且轉成mp3 (Python)- 2022
## 2022
這次回頭發現 PyTube 可以直接提取音訊
細節基本參考[Download Video in MP3 format using PyTube(GeeksforGeeks)](https://www.geeksforgeeks.org/download-video-in-mp3-format-using-pytube/)再做修改
首先安裝pytube
```
pip3 install pytube
```
::: warning
如果出現 ```ModuleNotFoundError: No module named 'pip'```
就去更新pip
執行 ``` sudo apt-get install python3-pip ```
:::
以下程式可直接取用 , 更改你的yt網址跟存mp3位置即可
```python=
from pytube import YouTube
import os
url = "https://www.youtube.com/watch?v=Dm9dUfvVhrQ"
target_path = "./Downloads"
yt = YouTube(url)
video = yt.streams.filter(only_audio=True).first()
out_file = video.download(output_path=target_path)
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
print("target path = " + (new_file))
print("mp3 has been successfully downloaded.")
```
url就是你要下載的youtube mp3 網址
target_path就是下載完要放的位址
執行完如下
![](https://i.imgur.com/FwsnyxE.png)
資料夾內對應生成mp3
![](https://i.imgur.com/kfooCvc.png)
:::info
\==================
以下是 2020 版本 , 可跳過
\==================
:::
## 2020
基本是參考[ccs96307大所寫的:Python 當中使用 pytube 下載 Youtube 的影片](https://clay-atlas.com/blog/2019/11/08/python-chinese-packages-pytube-moviepy-download-youtube-convert/)
不過當中遇到一些問題,紀錄如何解決。
環境:Ubuntu 18.04
使用pytube+moviepy
先安裝
```
sudo pip3 install pytube3
sudo pip3 install moviepy
```
要做的事情:
1. 抓YT影片
2. mp4轉檔mp3
### 1.抓YT影片
```python=
# -*- coding: utf-8 -*-
from pytube import YouTube
def progress(chunk,file_handle,bytes_remaining):
contentSize=video.filesize
size=contentSize-bytes_remaining
print('\r' + '[Download progress]:%.2f%%;\n' % (' ' * int(size*20/contentSize), ' '*(20-int(size*20/contentSize)), float(size/contentSize*100)), end='')
url='https://www.youtube.com/watch?v=9Sc-ir2UwGU'
yt=YouTube(url,on_progress_callback=progress)
video=yt.streams.first()
video.download()
```
url內就放你要抓的影片網址 progress內只是顯示進度條,要簡單的話三行就能搞定
```python=
# -*- coding: utf-8 -*-
from pytube import YouTube
url = 'https://www.youtube.com/watch?v=JwBXgJeqeOs'
YouTube(url).streams.first().download()
```
- 配合txt存網址列表可一次抓多首
- 可搭配音樂清單一次全抓
#### 遇到問題
```
Traceback (most recent call last):
File "/home/brad/.local/lib/python3.6/site-packages/pytube/extract.py", line 297, in apply_descrambler
for format_item in formats
File "/home/brad/.local/lib/python3.6/site-packages/pytube/extract.py", line 297, in <listcomp>
for format_item in formats
KeyError: 'url'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "DlYT2mp3.py", line 12, in <module>
yt=YouTube(url,on_progress_callback=progress)
File "/home/brad/.local/lib/python3.6/site-packages/pytube/__main__.py", line 92, in __init__
self.descramble()
File "/home/brad/.local/lib/python3.6/site-packages/pytube/__main__.py", line 132, in descramble
apply_descrambler(self.player_config_args, fmt)
File "/home/brad/.local/lib/python3.6/site-packages/pytube/extract.py", line 301, in apply_descrambler
parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
File "/home/brad/.local/lib/python3.6/site-packages/pytube/extract.py", line 301, in <listcomp>
parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
KeyError: 'cipher'
```
#### 如何解決?
爬文發現不少人有相同問題且有人給出解法
![](https://i.imgur.com/TMnwDXY.png)
簡單來說就是先看你的pytube裝在哪? 去資料夾內打開extract.py檔 找到函式apply_descrambler的301行,然後把
```python=
parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
```
改成
```python=
parse_qs(formats[i]["signatureCipher"]) for i, data in enumerate(formats)
```
- c記得改大寫
#### 詳細步驟
1. 輸入pip3 show pytube3
![](https://i.imgur.com/KNxYSO7.png)
看location位置在哪,進該目錄
![](https://i.imgur.com/iuCfwac.png)
看到pytube資料夾,進去
![](https://i.imgur.com/7YsLUx6.png)
發現extract. py 用你的IDE打開他,找到301行 改掉
![](https://i.imgur.com/vWwLyBm.png)
解決
### 2.mp4轉檔mp3
```python=
# -*- coding:utf-8 -*-
from moviepy.editor import *
filename='Kygo - Firestone.mp4'
targetname='Kygo - Firestone.mp3'
video=VideoFileClip(filename)
video.audio.write_audiofile(targetname)
```
#### 遇到問題
```
Traceback (most recent call last):
File "mp4tomp3.py", line 2, in <module>
from moviepy.editor import *
File "/usr/local/lib/python3.6/dist-packages/moviepy/editor.py", line 36, in <module>
from .video.io.VideoFileClip import VideoFileClip
File "/usr/local/lib/python3.6/dist-packages/moviepy/video/io/VideoFileClip.py", line 3, in <module>
from moviepy.audio.io.AudioFileClip import AudioFileClip
File "/usr/local/lib/python3.6/dist-packages/moviepy/audio/io/AudioFileClip.py", line 3, in <module>
from moviepy.audio.AudioClip import AudioClip
File "/usr/local/lib/python3.6/dist-packages/moviepy/audio/AudioClip.py", line 7, in <module>
from moviepy.audio.io.ffmpeg_audiowriter import ffmpeg_audiowrite
File "/usr/local/lib/python3.6/dist-packages/moviepy/audio/io/ffmpeg_audiowriter.py", line 7, in <module>
from moviepy.config import get_setting
File "/usr/local/lib/python3.6/dist-packages/moviepy/config.py", line 36, in <module>
FFMPEG_BINARY = get_exe()
File "/usr/local/lib/python3.6/dist-packages/imageio/plugins/ffmpeg.py", line 49, in get_exe
return imageio_ffmpeg.get_ffmpeg_exe()
File "/usr/local/lib/python3.6/dist-packages/imageio_ffmpeg/_utils.py", line 50, in get_ffmpeg_exe
"No ffmpeg exe could be found. Install ffmpeg on your system, "
RuntimeError: No ffmpeg exe could be found. Install ffmpeg on your system, or set the IMAGEIO_FFMPEG_EXE environment variable.
```
找不到ffmpeg.exe? 那就裝吧
#### 如何解決?
```
sudo apt update
sudo apt install ffmpeg
```
解決