main.py 2.3 KB
Newer Older
S
superyan 已提交
1
import streamlit as st
G
gepson 已提交
2 3 4
import requests
from tqdm import tqdm
import time
S
superyan 已提交
5

G
gepson 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
def download(url, filename, path, resolution):
    '''
    下载函数
    url: str 需要下载的文件链接
    filename: 储存的文件名
    path: 下载的文件储存地址
    resolution: 选择的分辨率(240, 480, 720, 1080)
    
    return: None
    '''
    headers = {
        'Referer': 'https://music.163.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }
    res = requests.get(url, headers=headers, stream=True)
    size = int(res.headers.get('Content-Length'))
    
    # 根据分辨率选择视频文件
    resol_map = {
        '240': '240',
        '480': '480',
        '720': '720',
        '1080': '1080',
    }
    resol_name = resol_map.get(resolution, None)
    if not resol_name:
        resol_name = '1080'
S
superyan 已提交
33

G
gepson 已提交
34 35 36 37 38 39 40 41 42 43
    with open(f'{path}/{resol_name}_{filename}', 'wb') as f:
        pbar = tqdm(
            total=size/1024/1024,
            unit='MB',
            desc=f'正在下载 {resolution}P 视频至 {path}/{resol_name}_{filename}')
        for chunk in res.iter_content(chunk_size=1024):
            f.write(chunk)
            pbar.update(1024/1024)
            time.sleep(0.001)
        pbar.close()
S
superyan 已提交
44

G
gepson 已提交
45 46 47 48 49 50 51 52 53 54
def check_url(url):
    '''
    检查链接是否为mtv链接
    url: str 视频链接
    
    return: bool
    '''
    if 'music.163.com/#/mv?id=' in url:
        return True
    return False
S
superyan 已提交
55 56

def main():
G
gepson 已提交
57
    st.title('网易云mtv下载工具')
S
superyan 已提交
58

G
gepson 已提交
59 60
    # 输入链接
    url = st.text_input('请输入mtv链接')
S
superyan 已提交
61

G
gepson 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    # 检查链接是否正确
    if not check_url(url):
        st.error('输入链接不是网易云mtv链接')
        return

    # 获取视频名称
    res = requests.get(url)
    title = res.text.split('<title>')[1].split(' - ')[0]
    st.write(f'视频名称:{title}')

    # 选择文件储存路径
    path = st.text_input('请选择储存路径', 'C:/Users/xxx/Downloads')
    st.write(f'储存路径:{path}')

    # 选择分辨率
    resolution = st.selectbox('请选择分辨率', ('240', '480', '720', '1080'))
    st.write(f'已选择分辨率:{resolution}P')

    # 开始下载
    if st.button('开始下载'):
        download(url, title, path, resolution)
        st.success('下载完成')
S
superyan 已提交
84 85

if __name__ == '__main__':
G
gepson 已提交
86
    main()