0%

酷我音乐爬虫

有趣的技术

思路:

代码:

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
import requests
import pprint
# 生成表格的模块
import prettytable as pt
import os
import re

if not os.path.exists('kuwo'):
os.mkdir('kuwo')
key=input("请输入你想查找的歌手or歌曲:")

url=f"https://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key={key}&pn=1&rn=30"
# 伪装请求头
#
headers={
'Accept':'application/json, text/plain, */*',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'zh-CN,zh;q=0.9',
'Connection':'keep-alive',
'Cookie':'Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1663154581; _ga=GA1.2.567394232.1663154581; _gid=GA1.2.2123499681.1663154581; _gat=1; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1663156972; kw_token=XATF666NGJP',
'csrf':'XATF666NGJP',
'Host':'www.kuwo.cn',
'Referer':'http://www.kuwo.cn/search/list?key=%E5%91%A8%E6%9D%B0%E4%BC%A6',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36',
}
response=requests.get(url=url,headers=headers)
# .JSON打印字典数值
# pprint.pprint(response.json())
# 获取到的歌曲数据源
json=response.json()
# 提取到对应的内容
json_data=json['data']['list']
# pprint.pprint(json_data)
count=0
table=pt.PrettyTable()
# 设置表头
table.field_names=['专辑','歌手','歌曲','rid']
# 创建一个列表,用来存放歌曲rid
info_list=[]

for list in json_data:
# 专辑
album=list['album']
# 歌手
artist=list['artist']
# 歌曲
name=list['name']
# rid
rid=list['rid']
# print(album,artist,name,rid)
table.add_row([album,artist,name,count])
info_list.append([album,artist,name,rid])
count+=1
print(table)

# 设置死循环
while True:
index=eval(input("请输入你想要下载的歌曲rid:"))
if index == -1:
break
# 下载的歌曲信息
download_info=info_list[index]
# print(download_info[3])
rid=download_info[3]
# song_url=f"https://www.kuwo.cn/api/v1/www/music/playUrl?mid={rid}&type=convert_url3&br=320kmp3"
song_url=f"https://www.kuwo.cn/api/v1/www/music/playUrl?mid={rid}&type=convert_url&httpsStatus=1"
# https://www.kuwo.cn/api/v1/www/music/playUrl?mid={rid}&type=convert_url&httpsStatus=1
# print(song_url)
# 找到他的mp3链接 用字典取值的方法 拿到付费歌曲的MP3链接
song_info=requests.get(url=song_url).json()['data']['url']
# print(song_info)
# 转换二进制格式便于保存数据
music=requests.get(url=song_info).content
title=re.sub(r'[\\/:*?"<>|]','',download_info[2])
#歌曲保存
with open(f"kuwo/{title}-{download_info[1]}.mp3",'wb')as f:
f.write(music)
print(f"{title},下载成功")

cookie的获取需要在自己电脑浏览器打开酷我首页,进入该网页源码获取

cookie获取完成后,还要更改里面kw_token为下面’csrf包含的 XATF666NGJP