---
# System prepended metadata

title: youtube downloader
tags: [Python]

---

---
tags: Python
---
youtube downloader
===

首先安裝pytube

```python
python -m pip install pytube
```

在 app.py裡面建立首頁路徑
```python
@app.route('/')
def index():
    return render_template('index.html')
```

在 app.py裡面建立submit 測試用路徑
```python
def submit():
    url = request.form['url']
    flash('下載成功！', 'success')
    return redirect(url_for('index'))
```

修改index.html，加入表單
```html
<form class="" action="/submit" method="post">
                      <label for="">input Url : </label>
                      
                      <input type="text" name="url" value="" placeholder="url">
                      <p></p>
                      <button class="btn btn-primary" type="submit">Submit</button>
                      <div></div>
                      {% if filename %}
                      <span>{{filename}}</span>
                      {% endif %}
                    </form>
```

html 加入flash 通知訊息
```html
<div>{% with messages = get_flashed_messages(with_categories=true) %}
                {% if messages %}
                    <ul class="flashes" style="list-style-type: none;">
                    {% for category, message in messages %}
                    <li class="alert alert-{{category}}">{{ message }}</li>
                    {% endfor %}
                          </ul>
                {% endif %}
                {% endwith %}</div>
```
app.py 加入submit 的route
```python
@app.route('/submit', methods=['POST', 'GET'])
def submit():
    url = request.form['url']
    yt = YouTube(url)

    # 指定要抓的格式，太高怕等太久
    video = yt.streams.filter(res='720p').first()
    # download完放到原本的檔案目錄
    video.download('./')
    flash('下載成功！', 'success')

    # filename = yt.title
    
    flash("失敗", 'danger')
    return redirect(url_for('index'))
```

修改 submit()，加入錯誤處理
```python
@app.route('/submit', methods=['POST', 'GET'])
def submit():
    url = request.form['url']
    try:
        yt = YouTube(url)

        # 指定要抓的格式，太高怕等太久
        video = yt.streams.filter(res='720p').first()
        # download完放到原本的檔案目錄
        video.download('./')
        flash('下載成功！', 'success')

        # filename = yt.title
    except pytube.exceptions.RegexMatchError:
        flash("失敗", 'danger')
        return redirect(url_for('index'))
    return redirect(url_for('index'))
```
