本帖最后由 silenough 于 2024-8-4 20:06 编辑
顺手优化下:
1、用索引做key,避免搜出多个同名歌曲,只能down最后一个,实际可能不是想找的song;
2、加个循环,用q和s控制,免得每次都要运行;
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import os
g_http = 'https://www.xxx.com' # 使用前把xxx替换下
def Menu(key):
global dic
url = f"{g_http}/s/{key}"
response = requests.get(url, headers=headers).text
soup = BeautifulSoup(response, "lxml")
song_list = soup.find_all("div", class_="row")
count = len(song_list)
print("共有歌曲:", count - 2)
for index, i in enumerate(song_list[1:count - 1]):
song_name = i.find("div", class_='col-5').find("a").text.replace("\n", "").replace("\r", "").replace(" ", "")
singer_name = i.find("div", class_='col-4').text.replace("\n", "").replace("\r", "").replace(" ", "")
url = i.find("div", class_='col-3').find("a").get("href")
down_url = g_http + url
dic[index] = (song_name, down_url)
print(f"序号:{index}, 歌曲:{song_name}, 歌手:{singer_name}")
def Download(index):
url = dic[index][1]
id = url.split('/')[4]
data_url = f'{g_http}/api/play_url?id={id}&json=1'
response = requests.get(data_url, headers=headers).json()
sava_url = response['data']['url']
sava(sava_url, dic[index][0])
def sava(song_down, song_name):
if not os.path.exists("./歌曲"):
os.mkdir("./歌曲")
response = requests.get(song_down, headers=headers).content
with open(f"./歌曲/{song_name}.mp3", "wb") as f:
f.write(response)
print("下载成功")
if __name__ == '__main__':
while (True):
key = input("输入歌曲搜索关键词:")
if key == "q":
exit(0)
ua = UserAgent().random
headers = {
"User-Agent": ua
}
dic = {}
Menu(key)
down_loop = True
while (down_loop):
key2 = input("输入下载歌曲序号:")
if key2 == "q":
exit(0)
if key2 == "s":
break
Download(int(key2))
|