想聽一首歌好難?程序員教你一鍵下載


1.首先要先安裝一下Python第三方庫

  • requests #pip install requests
  • prettytable # pip install PrettyTable

2.使用的開發環境:

  • 版 本: python 3.8
  • 編輯器:pycharm 2021.2

3.先給你們來一個思路

在這里插入圖片描述
不管你以后爬那個網站,安裝這個思路就對了!

注意:不建議學習bs4,懂的都懂

4.接下來,咱們正式開始

今天咱們就搞定它

# *改成k
url='https://www.*uwo.cn/'

導入模塊

import requests
from urllib import parse
import prettytable as pt

添加請求頭

headers = {
    # 瀏覽器基本信息
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
    # 辨別用戶的身份
    'Cookie': '*',
    # 認證令牌
    'csrf': 'C713RK6IJ8J',
    # 指定的請求資源的域名
    # *改成k
    'Host': 'www.*uwo.cn',
    # 用來跟蹤Web請求來自哪個頁面,是從什么網站來的。
    'Referer': 'http://www.*uwo.cn/search/list?key='+searchKey
}

下載指定歌曲:

# *改成k
url = f'http://www.*uwo.cn/api/www/search/searchMusicBykeyWord?key={searchKey}&pn=1&rn=30'
json_data = requests.get(url=url, headers=headers).json()
song_list = json_data['data']['list']
count = 0
info_list = []
tb = pt.PrettyTable()
tb.field_names = ['序號', '歌名', '歌手', '專輯']
for song in song_list:
    singer_name = song['artist']
    song_name = song['name']
    album_name = song['album']
    rid = song['rid']
    info_list.append([rid, song_name, singer_name])
    tb.add_row([count, song_name, singer_name, album_name])
    # *改成k
    song_info_url = f'https://www.*uwo.cn/api/v1/www/music/playUrl?mid={rid}&type=convert_url3&br=320kmp3'
    music_url = requests.get(song_info_url, headers=headers).json()['data']['url']
    music_data = requests.get(music_url).content
    with open(f'download/{singer_name}-{song_name}.mp3', mode='wb') as f:
        f.write(music_data)
        print(f'{song_name}', '下載完成!!!')
    count += 1
print(tb)

后面再加一個功能,實現自定義下載:

    input_index = eval(input("請輸入要下載歌曲的序號(-1退出): "))
    if input_index == -1:
        break
    download_info = info_list[input_index]
    # 流暢音質  128k
    # 高頻音質  192k
    # 超品音質  320k
    # *改成k
    song_info_url = f'https://www.*uwo.cn/api/v1/www/music/playUrl?mid={download_info[0]}&type=convert_url3&br=320kmp3'
    music_url = requests.get(song_info_url, headers=headers).json()['data']['url']
    music_data = requests.get(music_url).content
    with open(f'download/{download_info[1]}-{download_info[2]}.mp3', mode='wb') as f:
        f.write(music_data)
        print(f'{download_info[1]}', '下載完成!!!')

5.效果展示:

在這里插入圖片描述

學會了嘛?需要源碼可以留言、私信我。

結尾給大家推薦一個非常好的學習教程,希望對你學習Python有幫助!

Python基礎入門教程推薦:←點擊左邊藍色文字就可以跳轉觀看了

Python爬蟲案例教程推薦:←點擊左邊藍色文字就可以跳轉觀看了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM