仅供参考学习,禁止用于非法用途
目录
安装库
requests selenium webdriver
以及 PhantomJS
创建主目录Music_Downloader
创建文件 Music_Downloader.py
在同目录下创建包Downloader
在包中创建文件
kugou.py
kuwo.py
wangyiyun.py
QQMusic.py
qianqian.py
类似这样
然后就可以快乐的书写我们的代码了
kugou.py
from urllib.parse import *
import requests
import os
import json
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
'referer': 'https://www.kugou.com/yy/html/search.html',
'cookie': 'kg_mid=54466227d384411d3637dfa321b337d6; kg_dfid=1Hvl060iZWHn0cXnq12YuJP5; kg_dfid_collect=d41d8cd98f00b204e9800998ecf8427e; Hm_lvt_aedee6983d4cfc62f509129360d6bb3d=1585209276,1585279988,1585380359; Hm_lpvt_aedee6983d4cfc62f509129360d6bb3d=1585380377',
}
def get_id(url):
r = requests.get(url, headers=headers).text
dict = json.loads(r[43:-2])
data = dict['data']['lists']
names = []
hashes = []
ids = []
for item in data:
names.append(item['FileName'].replace('', '').replace('', ''))
hashes.append(item['FileHash'])
ids.append(item['AlbumID'])
return names, hashes, ids
def download_music(name, hash, id):
url = f'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19108859518011228213_1585286241467&hash={hash}&album_id={id}&dfid=1Hvl060iZWHn0cXnq12YuJP5&mid=54466227d384411d3637dfa321b337d6&platid=4&_=1585286241469'
r = requests.get(url, headers=headers).text
dict = json.loads(r[41:-2])
play_url = dict['data']['play_url']
try:
with open('%s.mp3' % name, 'wb') as f:
f.write(requests.get(play_url).content)
print("%s 下载完成" % name)
except:
pass
def Kugou_Downloader():
music_name = input("输入你要下载的歌名或歌手>>>")
url = f'https://songsearch.kugou.com/song_search_v2?callback=jQuery1124001117916144825526_1585380377159&keyword={quote(music_name)}&page=1&pagesize=10&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection=1&privilege_filter=0&_=1585380377161'
if not os.path.exists('。/music'):
os.mkdir('./music')
os.chdir('./music')
print("下载位置:%s" % os.getcwd())
names = get_id(url)[0]
hashes = get_id(url)[1]
ids = get_id(url)[2]
for i in range(len(names)):
name = names[i]
hash = hashes[i]
id = ids[i]
download_music(name, hash, id)
os.chdir('..')
kuwo.py
import requests
from urllib.parse import quote
import json
import os
def get_song_id(url, headers):
r = json.loads(requests.get(url, headers=headers).text)
data = r['data']['list']
singers = []
names = []
ids = []
for item in data:
singers.append(item['artist'])
names.append(item['name'])
ids.append(item['rid'])
return singers, names, ids
def download_song(singer, name, rid, headers):
url = f'http://www.kuwo.cn/url?format=mp3&rid={rid}&response=url&type=convert_url3&br=128kmp3&from=web&t=1585283715475&reqId={rid}'
r = json.loads(requests.get(url, headers=headers).text)
video_url = r['url']
file = open('%s %s.mp3' % (name, singer), 'wb')
file.write(requests.get(video_url).content)
file.close()
print("%s %s 下载完成" % (name, singer))
def Kuwo_Downloader():
music_name = input("输入你要下载的歌名或歌手>>>")
url = f'http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key={quote(music_name)}&pn=1&rn=10&reqId=23529c50-6fe2-11ea-99be-470e4c105e4c'
headers = {
'Cookie': '_ga=GA1.2.531172689.1585271847; _gid=GA1.2.1879378667.1585271847; gtoken=P4vBP1VaNQmV; gid=b29e452c-a559-42d9-8b94-f0ec588c2f7c; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1585271847,1585272586,1585272601,1585282753; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1585282753; _gat=1; kw_token=MGLE4XIH6LK',
'csrf': 'MGLE4XIH6LK',
'Host': 'www.kuwo.cn',
'Referer': f'http://www.kuwo.cn/search/list?key={quote(music_name)}',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
}
if not os.path.exists('./music'):
os.mkdir('./music')
os.chdir('./music')
print("下载位置:%s" % os.getcwd())
singers = get_song_id(url, headers)[0]
names = get_song_id(url, headers)[1]
ids = get_song_id(url, headers)[2]
for i in range(len(singers)):
singer = singers[i]
name = names[i]
id = ids[i]
download_song(singer, name, id, headers)
os.chdir('..')
wangyiyun.py
from selenium import webdriver
from urllib.parse import quote
import os
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
'Referer': 'https://music.163.com/',
}
class Wangyiyun_Music:
idlist = []
namelist = []
singerlist = []
def __init__(self):
self.music_name = input("输入你要下载的歌名或作者>>>")
self.url = f'https://music.163.com/#/search/m/?s={quote(self.music_name)}&type=1'
def get_song_id(self):
self.browser = webdriver.PhantomJS()
self.browser.get(self.url)
self.browser.switch_to.frame('g_iframe')
self.req = self.browser.find_element_by_class_name('srchsongst')
self.song_id = self.req.find_elements_by_xpath('.//div[@class="item f-cb h-flag "]/div[2]//a')
for item in self.song_id:
Wangyiyun_Music.idlist.append(item.get_attribute('href').split('=')[1])
self.song_name = self.req.find_elements_by_xpath('.//div[@class="item f-cb h-flag "]/div[2]//b')
for item in self.song_name:
Wangyiyun_Music.namelist.append(item.get_attribute('title'))
self.song_singer = self.req.find_elements_by_xpath('.//div[@class="item f-cb h-flag "]/div[4]//a')
for item in self.song_singer:
Wangyiyun_Music.singerlist.append(item.text)
def download_song(self):
Wangyiyun_Music.get_song_id(self)
self.base_url = 'http://music.163.com/song/media/outer/url?id={}.mp3'
self.video_url = []
for item in Wangyiyun_Music.idlist:
self.video_url.append(self.base_url.format(item))
if not os.path.exists('./music'):
os.mkdir('./music')
os.chdir('./music')
print("下载位置:%s" % os.getcwd())
for i in range(len(self.video_url)):
try:
self.name = Wangyiyun_Music.namelist[i]
self.singer = Wangyiyun_Music.singerlist[i]
self.video = self.video_url[i]
file = open('%s %s.mp3' % (self.name, self.singer), 'wb')
file.write(requests.get(self.video, headers=headers).content)
file.close()
print("%s %s 下载成功" % (self.name, self.singer))
except:
pass
QQMusic.py
import requests
import os
from urllib.parse import urlencode
def download_QQMusic():
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
'referer': 'https://y.qq.com/portal/search.html',
}
music_name = input("输入要下载的歌名或歌手>>>")
data = {
'ct': '24',
'qqmusic_ver': '1298',
'new_json': '1',
'remoteplace': 'txt.yqq.song',
'searchid': '72054918315855694',
't': '0',
'aggr': '1',
'cr': '1',
'catZhida': '1',
'lossless': '0',
'flag_qc': '0',
'p': '1',
'n': '10',
'w': music_name,
'g_tk_new_20200303': '2057904734',
'g_tk': '2057904734',
'loginUin': '1571120423',
'hostUin': '0',
'format': 'json',
'inCharset': 'utf8',
'outCharset': 'utf - 8',
'notice': '0',
'platform': 'yqq.json',
'needNewCode': '0',
}
base_url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?' + urlencode(data)
r = requests.get(base_url, headers=headers).json()
song_list = r['data']['song']['list']
names = []
singers = []
midlist = []
for item in song_list:
names.append(item['title'])
midlist.append(item['mid'])
singers.append(item['singer'][0]['name'])
# ------------------------------------------------------------------------------------------------------
purl_list = []
for mid in midlist:
url = f'https://u.y.qq.com/cgi-bin/musicu.fcg?-=getplaysongvkey6455258874010792&g_tk=2057904734&loginUin=1571120423&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8¬ice=0&platform=yqq.json&needNewCode=0&data=%7B%22req%22%3A%7B%22module%22%3A%22CDN.SrfCdnDispatchServer%22%2C%22method%22%3A%22GetCdnDispatch%22%2C%22param%22%3A%7B%22guid%22%3A%225916370708%22%2C%22calltype%22%3A0%2C%22userip%22%3A%22%22%7D%7D%2C%22req_0%22%3A%7B%22module%22%3A%22vkey.GetVkeyServer%22%2C%22method%22%3A%22CgiGetVkey%22%2C%22param%22%3A%7B%22guid%22%3A%225916370708%22%2C%22songmid%22%3A%5B%22{mid}%22%5D%2C%22songtype%22%3A%5B0%5D%2C%22uin%22%3A%221571120423%22%2C%22loginflag%22%3A1%2C%22platform%22%3A%2220%22%7D%7D%2C%22comm%22%3A%7B%22uin%22%3A1571120423%2C%22format%22%3A%22json%22%2C%22ct%22%3A24%2C%22cv%22%3A0%7D%7D'
response = requests.get(url, headers=headers).json()
s = response['req_0']['data']['midurlinfo'][0]['purl']
purl_list.append(s)
play_url = ['https://isure.stream.qqmusic.qq.com/' + x for x in purl_list]
if not os.path.exists('./music'):
os.mkdir('./music')
os.chdir('./music')
print("下载位置:%s" % os.getcwd())
for i in range(len(names)):
try:
name = names[i]
singer = singers[i]
url = play_url[i]
file = open('%s %s.mp3' % (name, singer), 'wb')
file.write(requests.get(url, headers=headers).content)
file.close()
print("%s %s 保存成功" % (name, singer))
except:
pass
os.chdir('..')
qianqian.py
import requests
import re
import json
from urllib.parse import *
import os
def get_id(music_name):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
'Host': 'music.taihe.com',
'Referer': 'http://music.taihe.com/',
'Cookie': 'BAIDUID=E23486F8F8E78C1989B3691059C374AA:FG=1; u_lo=0; u_id=; u_t=; log_sid=1585711800186E23486F8F8E78C1989B3691059C374AA; Hm_lvt_d0ad46e4afeacf34cd12de4c9b553aa6=1585278402,1585278908,1585711802; tracesrc=-1%7C%7C-1; __qianqian_pop_tt=4; Hm_lpvt_d0ad46e4afeacf34cd12de4c9b553aa6=1585712626',
}
url = f'http://music.taihe.com/search?key={quote(music_name)}'
html = requests.get(url, headers=headers).text
return re.findall(re.compile(r'\{ "id": "(.*?)" }'), html)
def download(id):
url = f'http://musicapi.taihe.com/v1/restserver/ting?method=baidu.ting.song.playAAC&format=jsonp&callback=jQuery172036047943074942945_1585711904941&songid={id}&from=web&_=1585711907963'
r = requests.get(url).text
data=r[r.index('{'):-2]
try:
data=json.loads(data)
name = data['songinfo']['title']
singer = data['songinfo']['compose']
play_url = data['bitrate']['file_link']
with open("%s %s.mp3"%(name,singer),'wb') as f:
f.write(requests.get(play_url).content)
print("%s %s 保存完成"%(name,singer))
except:
pass
def qianqian_download():
if not os.path.exists('./music'):
os.mkdir('./music')
os.chdir('./music')
music_name = input("输入你要下载的歌名或歌手>>>")
print("下载地址 %s"%os.getcwd())
for item in get_id(music_name):
download(item)
os.chdir('..')
Music_Dpwnloader.py
import Downloader.kugou
import Downloader.kuwo
import Downloader.wangyiyun
import Downloader.QQMusic
import Downloader.qianqian
def main():
while True:
print('''\n请选择下载方式
1:酷狗音乐;
2:酷我音乐;
3:网易云音乐;
4:QQ音乐;
5:千千音乐
(输入q退出程序)''')
guess = input("\n请输入下载器(填序号)>>>")
if guess == '1':
Downloader.kugou.Kugou_Downloader()
go = input("继续下载(y/n)").upper()
if go == 'Y' or go == 'YES':
continue
else:
exit("退出")
elif guess == '2':
Downloader.kuwo.Kuwo_Downloader()
go = input("继续下载(y/n)").upper()
if go == 'Y' or go == 'YES':
continue
else:
exit("退出")
elif guess == '3':
wangyiyunmusic = Downloader.wangyiyun.Wangyiyun_Music()
wangyiyunmusic.download_song()
go = input("继续下载(y/n)").upper()
if go == 'Y' or go == 'YES':
continue
else:
exit("退出")
elif guess == '4':
Downloader.QQMusic.download_QQMusic()
go = input("继续下载(y/n)").upper()
if go == 'Y' or go == 'YES':
continue
else:
exit("退出")
elif guess == '5':
Downloader.qianqian.qianqian_download()
go = input("继续下载(y/n)").upper()
if go == 'Y' or go == 'YES':
continue
else:
exit("退出")
else:
exit()
if __name__ == '__main__':
print("*" * 21 + "音乐下载器" + "*" * 21)
main()
本人小白,写的不好请见谅