虾米音乐下载

import requests
import re
from bs4 import BeautifulSoup
from string import punctuation
import os
header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
def str2url(s):
num_loc = s.find('h')
rows = int(s[0:num_loc])
strlen = len(s) - num_loc
cols = int(strlen/rows)
right_rows = strlen % rows
new_s = s[num_loc:]
output = ''
for i in range(len(new_s)):
x = i % rows
y = int(i / rows)
p = 0
if x <= right_rows:
p = x * (cols+1) + y
else:
p = right_rows * (cols+1) + (x - right_rows) * cols + y
output += new_s[int(p)]
return requests.utils.unquote(output).replace('^', '0')

def filtrate(G):
return G.strip().replace('<b class="key_red">','').replace('</b>','')
while True:
song_name = input('请输入歌曲名字')
sou = 'http://www.xiami.com/search?key='+song_name+'&pos=1'
song_list = requests.get(sou,headers=header).text
demo = re.compile('<td class="song_name">.*?<a.*?>(.*?)</a>.*?</td>.*?<td class="song_artist">.*?<a.*?>(.*?)</a>.*?</td>.*?<td class="song_album">.*?<a.*?>(.*?)</a>.*?</td>.*?play\((.*?)\)',re.S)
lists = demo.findall(song_list)
n = 1
for a,b,c,d in lists:
print(n,filtrate(a),filtrate(b),filtrate(c))
n = n+1
choice = input('请选择歌曲序号')
m = 1
for a,b,c,d in lists:
d= d.split(',')[0].replace("'","")
if choice==str(m):
songs = 'http://www.xiami.com/widget/xml-single/uid/0/sid/'+str(d)
print(songs)
xml_contents = requests.get(songs,headers=header).text
demo = re.compile('CDATA\[(.*?)\]', re.S)
lists = demo.findall(xml_contents)
s = lists[4]
song_url = str2url(s)
w = ''
for word in lists[0]:
if word not in punctuation:
w = w+word
if os.path.isfile('F:\\15\\top100\\'+ w+lists[2]+lists[3]+'.mp3'):
print(w + lists[2] + lists[3] + '已存在')
else:
print('正在下载' + filtrate(a) + '请等待')
songs = requests.get(song_url, headers=header).content
op = open('F:\\15\\top100\\' + w + lists[2] + lists[3] + '.mp3', 'wb')
op.write(songs)
op.close()
print('已下载' + filtrate(a) + '请查看')
m = m + 1
song_name = input('请输入歌曲名字')

猜你喜欢

转载自www.cnblogs.com/mypath/p/9020164.html
今日推荐