前言
現在的音樂平台,很多歌曲,要開VIP才能聽,這沒什么。
但是都開會員了,下載歌曲還要另外收費,這我就不能忍了
是你們逼我動手的
- requests
- urllib.parse
- prettytable 打印表格 控制台 輸出的表格變好看
- 版本:anaconda5.2.0 (python3.6.5)
- 編輯器: pycharm
# 發送網絡請求的第三方模塊 import requests # 格式化打印的內置模塊 import pprint import prettytable as pt
url = f'http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key={searchKey}&pn=1&rn=30'
遭遇到了反爬,添加一些偽裝,讓酷我音樂認為我當前是一個瀏覽器
headers = { # 辨別 用戶的身份 'Cookie': 'Hm_lvt_cdb524f42f0ce19b1fasd071123a4797=1631621725; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1631621725; _ga=GA1.2.861666777.1631621725; _gid=GA1.2.433324540.1631621725; _gat=1; kw_token=6YMC3KUGVVO', # 指定請求資源的域名 'Host': 'www.kuwo.cn', # 認證令牌 'csrf': '6YMC3KUGVVO', # 防盜鏈: 用來跟蹤web請求來自哪個頁面 是從哪個網站上面來的 'Referer': 'http://www.kuwo.cn/search/list?key=%E5%91%A8%E7%9D%B0%E4%BC%A6', # 瀏覽器的基本信息 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36' } requests.get(url, headers=headers).json()
key:關鍵詞,用url解碼歌手名字
searchKey = input('請輸入你要下載的歌手或者歌曲名:') 取值,並表格式輸出內容 json_data = requests.get(url, headers=headers).json() song_list = json_data['data']['list'] info_list = [] # 歌曲信息 (rid 歌曲名字 歌手名稱) count = 0 # 歌曲序號 tb = pt.PrettyTable() # 實例化一個對象 tb.field_names = ['序號', '歌名', '歌手', '專輯'] for song in song_list: album = song['album'] # 專輯名稱 artist = song['artist'] # 歌手名稱 name = song['name'] # 歌曲名字 rid = song['rid'] # 歌曲id info_list.append([rid, name, artist]) # 音樂下載要用的列表 tb.add_row([count, name, artist, album]) # 表格多行追加 count += 1 print(tb)
while True: input_index = eval(input('請輸入要下載歌曲的序號(-1退出):')) if input_index == -1: break download_info = info_list[input_index] song_info_url = f'https://www.kuwo.cn/url?rid={download_info[0]}&type=convert_url3&br=320kmp3' music_url = requests.get(song_info_url, headers=headers).json()['url'] music_data = requests.get(music_url).content with open(f'C:/Users/Administrator/Desktop/新建文件夾/{download_info[1]}-{download_info[2]}.mp3', mode='wb') as f: f.write(music_data) print(f'{download_info[1]}下載完成!!!')