-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
164 lines (143 loc) · 6.75 KB
/
main.py
1
2
3
4
5
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# _*_coding:utf-8_*_
# author:gq
#version:1.0
#
# 2109-08-10 适应python3.6 modify by:[email protected]
import re
import urllib
import urllib.request
import json
import sys
import os
import LogUtil
# 运行配置
TOP_DOWNLOAD_NUMBER = 1 # 搜索下载排名多少的歌曲,2就下载前两个,最大只能设置20
SEARCH_KEYWORDS = [
"爱你一万年",
]
def search_music(song_name):
# print "搜索的歌名:" + song_name.encode("utf-8")
header = {
"authority": "c.y.qq.com",
"method": "GET",
"path": "/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song"
"&searchid=62072551069125820&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=20&w=%s"
"&g_tk=5381&jsonpCallback=searchCallbacksong2143&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8"
"&outCharset=utf-8¬ice=0&platform=yqq&needNewCode=0" % song_name,
"scheme": 'https',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-language': 'zh-CN,zh;q=0.9',
'cache-control': 'max-age=0',
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
# url地址可以浏览器分析获取,主要是&w参数
url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.song' \
'&searchid=62072551069125820&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=20&w=%s' \
'&g_tk=5381&jsonpCallback=searchCallbacksong&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8' \
'&outCharset=utf-8¬ice=0&platform=yqq&needNewCode=0' % song_name
LogUtil.i('Searching:' + url + '\n')
request = urllib.request.Request(url, headers=header)
try:
html = urllib.request.urlopen(request).read()
except Exception as e:
print ('Download error:', e, '\n')
html = None
return html
def parseResponse(html):
# 解析searchCallbacksong(),括号中的内容
result = re.findall(".*searchCallbacksong\((.*)\).*", html.decode('utf8'))
#print(str(result[0]))
json_str = result[0]
LogUtil.d("reponse解析的json字符串:" + json_str)
#print(json_str)
json_str2 = str(json_str)
jsonObject = json.loads(json_str2) # 转化为python dict
# print type(jsonObject)
# print jsonObject["data"]["song"]["list"]
for index, item in enumerate(jsonObject['data']['song']['list']):
if ((index + 1) > TOP_DOWNLOAD_NUMBER):
LogUtil.d("设置最大下载的数量为:" + str(TOP_DOWNLOAD_NUMBER))
break;
elif(TOP_DOWNLOAD_NUMBER>=1):
media_mid = item["file"]["media_mid"]
mid = item["mid"]
if TOP_DOWNLOAD_NUMBER == 1 :
save_filename = item["name"] + ".m4a"
else:
save_filename = item["name"] + "-" + str(index + 1) + ".m4a"
LogUtil.d(str(index) + " media_mid: " + media_mid + "; mid:" + mid + "; name:" + save_filename)
get_vkey(mid, media_mid, save_filename)
def get_vkey(mid, media_mid, save_filename):
header = {
"authority": "c.y.qq.com",
"method": "GET",
"path": "/base/fcgi-bin/fcg_music_express_mobile3.fcg?g_tk=5381&jsonpCallback=MusicJsonCallback"
"&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8¬ice=0&platform=yqq"
"&needNewCode=0&cid=205361747&callback=MusicJsonCallback2346403861098214&uin=0&songmid=%s"
"&filename=C400%s.m4a&guid=5789371178" % (mid, media_mid),
"scheme": 'https',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'accept-language': 'zh-CN,zh;q=0.9',
'cache-control': 'max-age=0',
"referer": "https://y.qq.com/portal/player.html",
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
# url地址可以浏览器分析获取,主要是&w参数
url = 'https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg?g_tk=5381&jsonpCallback=MusicJsonCallback' \
'&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8¬ice=0&platform=yqq&needNewCode=0' \
'&cid=205361747&callback=MusicJsonCallback&uin=0&songmid=%s&filename=C400%s.m4a' \
'&guid=5789371178' % (mid, media_mid)
LogUtil.i('get vkey :' + url + '\n')
request = urllib.request.Request(url, headers=header)
try:
html = urllib.request.urlopen(request).read()
result = re.findall(".*MusicJsonCallback\((.*)\).*", str(html))
json_str = result[0]
LogUtil.d("get_vkey解析的字符串为:" + json_str)
jsonObject = json.loads(json_str) # 转化为python dict
filename = jsonObject["data"]["items"][0]["filename"]
songmid = jsonObject["data"]["items"][0]["songmid"]
vkey = jsonObject["data"]["items"][0]["vkey"]
LogUtil.d("filename=" + filename + " ;songmid:" + songmid + " ;vkey:" + vkey)
download_m4a(filename, vkey, save_filename)
except Exception as e:
print ('vkey error:', e, '\n')
html = None
return html
def download_m4a(filename, vkey, save_filename):
header = {
'Accept': '*/*',
'Accept-Encoding': 'identity;q=1, *;q=0',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Connection': 'keep-alive',
'cache-control': 'max-age=0',
"Host": "dl.stream.qqmusic.qq.com",
"Range": "bytes=0-",
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
}
# url地址可以浏览器分析获取,主要是&w参数
url = 'http://dl.stream.qqmusic.qq.com/%s?vkey=%s&guid=5789371178&uin=0&fromtag=66' % (filename, vkey)
LogUtil.i('Downloading m4a :' + url + '\n')
request = urllib.request.Request(url, headers=header)
try:
html = urllib.request.urlopen(request).read()
#print(type(html))
#print(save_filename)
write_file(save_filename.encode().decode('utf8'), html)
except Exception as e:
print ('m4a error:', e, '\n')
html = None
return html
def write_file(save_filename, data):
if not os.path.exists(path):
os.makedirs(path)
save_filename = path + save_filename
with open(save_filename, "wb") as code:
code.write(data)
path = sys.path[0] + os.sep + "Music" + os.sep
if __name__ == "__main__":
for keyword in SEARCH_KEYWORDS:
keyword = urllib.parse.quote(keyword)
html = search_music(keyword)
parseResponse(html)
print ("完成!文件的保存路径:" + path)