提交 7ea8e467 编写于 作者: 渔戈's avatar 渔戈

更新QQ音乐/QQ音乐.py

上级
#Time:2020/04/26
#author:渔戈
import requests
import json
import re
import os
import time
# 词云
import jieba.analyse #结巴分析,#pip install jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from wordcloud import ImageColorGenerator # 获取图片像素值
from matplotlib.image import imread #读取图片 #pip install matplotlib
headers = {
"origin": "https://y.qq.com",
"pragma": "no-cache",
"referer": "https://y.qq.com/portal/search.html",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
}
datas = []
'''读取音乐id'''
def start_url():
global path
global name
global singer
num = 20
name = input('请输入歌名:')
path = f'F:\\接单\\qq音乐\\{name}'
if not os.path.isdir(path): # 判断有没有这个路径
os.mkdir(path)
url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?p=1&n=%d&w=%s' % (num, name)
# 搜索音乐
response = requests.get(url, headers=headers)
html = response.text
html = html[9:]
html = html[:-1]
'''获取音乐id'''
js = json.loads(html)
songlist = js['data']['song']['list']
for song in songlist:
songid = song['songid'] #id
songmid = song['songmid'] #mid
names = song['songname']#歌曲名
singer = song['singer'][0]['name_hilight'] #演唱者
print('歌名:',names,'演唱者:',singer,'歌曲id:',songid,'歌曲mid:',songmid)
'''获取音乐链接'''
def getVkey():
items = []
global name
global songid
guid = '2240306200'
uin = '123456789'
print('开始获取资源')
''' 获取vkey,和purl'''
names = name
songid =input('请输入你所要下载歌曲的id:')
songmid = input('请输入所要下载歌曲的mid:')
items.append([names,songid,songmid])
keyUrl = 'https://u.y.qq.com/cgi-bin/musicu.fcg?&data={"req":{"param":{"guid":" %s"}},"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"%s","songmid":["%s"],"uin":"%s"}},"comm":{"uin":%s}}'%(guid,guid,songmid,uin,uin)
response = requests.get(keyUrl, headers=headers)
if response.status_code == 200:
keyjs = json.loads(response.text)
'''获取链接:如C400004WZXOc20rcug.m4a?guid=2240306200&vkey=8E83E45B2B4D236F6758F8814E43446CABC516DC057C0F95EAA46637FD2FA536465922C416CDB9E619FBF8BCF42642184AE8BA8B2C4A9BF1&uin=6273&fromtag=66'''
purl = keyjs['req_0']['data']['midurlinfo'][0]['purl']
# 拼凑资源url
url = 'http://dl.stream.qqmusic.qq.com/' + purl
datas.append((name, url)) # 存储音乐名称和链接
print('获取的音乐链接如下:')
print(url)
print('资源地址获取成功')
return items
'''下载音乐'''
def downloadMusic():
global path
path =path
print('正在下载音乐,请骚等...')
for i in datas:
url = i[1]
response = requests.get(url,headers=headers)
music = response.content
name = i[0] + '.mp3'
# print(name)#查看文件名
with open(path+f'\\{name}', 'wb') as f:
f.write(music)
print('下载成功')
f.close()
'''获取评论信息'''
def get_music_comment(items):
global name
global path
path=path
name =name
comment_list = []
page = int(input('请输入所要获取的评论页数:'))
for i in range(0,page):
try:
time.sleep(2)
for item in items:
topid = item[1] # id号
mid = item[2] # mid号
header = {
"referer": f"https://y.qq.com/n/yqq/song/{mid}.html", # referer需要变换mid参数 不然无返回数据
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36",
}
url = "https://c.y.qq.com/base/fcgi-bin/fcg_global_comment_h5.fcg?g_tk_new_20200303=744858319&g_tk=744858319&loginUin=123456789&hostUin=0&format=json&inCharset=utf8&outCharset=GB2312&notice=0&platform=yqq.json&needNewCode=0&cid=205360772&reqtype=2&biztype=1&topid={}&cmd=8&needmusiccrit=0&pagenum={}&pagesize=25&lasthotcommentid=song_237270257_1152921504841432379_1574944849_1152921504647110724_1587615596&domain=qq.com&ct=24&cv=10101010" .format(topid,i)
response = requests.get(url=url,headers=header)
print('正在获取第{}页链接'.format(i+1))
print(response.url)
datas = response.json()['comment']['commentlist']
for data in datas:
nick = data['nick'] # 评论者
comments = data['rootcommentcontent'] # 评论信息
com_data = nick + ':' + comments
comment_list.append(com_data)
print(nick,':',comments)
with open(path + f'\\{name}评论.txt', 'a', encoding='utf-8') as f:
f.write(com_data) # 写入评论信息
except Exception as e:
continue
f.close()
return comment_list
'''词云图'''
def wordcloud(comment_list):
print('正在生成词云图:')
global name
global path
path =path
name =name
comment = ''.join(comment_list) # 将列表变成字符串数据
back_img = imread("小老虎.jpg") # 读取图片
img_colors = ImageColorGenerator(back_img) # 生成图片的像素值
tags = jieba.analyse.extract_tags(comment, topK=1000, withWeight=True, allowPOS=()) # 使用结巴分析提取标签
data = {item[0]: item[1] for item in tags} # tags是数组形式,把数组转为词频字典
word_cloud = WordCloud(font_path="c:\windows\Fonts\simhei.ttf", # 字体,本电脑c盘下的黑体,这样才能显示中文
background_color="white", # 图片的背景颜色
max_words=1000, # 字体个数,不超过上面选取的个数
max_font_size=100, # 字体大小
width=1920, # 图片像素宽
mask=back_img, # 使用图片蒙板,上面读取图片的像素
height=1080).generate_from_frequencies(data) # 传入上面的词频结果
wc_color = word_cloud.recolor(color_func=img_colors) # 替换默认的字体颜色
plt.figure(figsize=(12, 12)) # 创建一个图形实例,设置画布大小
plt.imshow(word_cloud, interpolation='bilinear') # 插值='双线性'
plt.axis("off") # 不显示坐标尺寸
word_cloud.to_file(path+f'\\{name}.png') # 保存图片
plt.show()
print('词云图生成成功!')
'''歌词'''
def lyric(items):
for i in items:
id = str(i[1]) # id 用于添加进歌词请求参数中
name = i[0] # 歌名
mid = i[2] #mid
# print(id,song_name)
headers = {
"origin": "https://y.qq.com",
"pragma": "no-cache",
"referer": f"https://y.qq.com/n/yqq/song/{mid}.html",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36",
}
url = 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_yqq.fcg?nobase64=1&musicid={}&-=jsonp1&g_tk_new_20200303=744858319&g_tk=744858319&loginUin=123456789&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0'.format(id)
response = requests.get(url, headers=headers)
try:
lyric = response.json()['lyric'] # 歌词
lyric = re.sub('\[.*?\]', '\n', lyric) # re.sub替换掉多余的列表数据
lyric = re.sub('[ 
G.E.M./T-Ma ]', '', lyric).strip() # 替换掉多余字符,去掉空白行
print('已成功获取到音乐歌词:')
print(lyric)
with open(path + f'\\{name}' + '.txt', 'w', encoding='utf-8') as f:
f.write(lyric) # 写入歌词
f.close()
except Exception as e:
print('歌词获取失败:{}'.format(e))
if __name__ == '__main__':
start_url()
items=getVkey()
downloadMusic()
comment_list=get_music_comment(items)
wordcloud(comment_list)
lyric(items)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册