开发环境
python3.9.7 pycharm2021.2
代码如下,安装类库,运行代码即可看到效果
import time
import requests
from lxml import etree
import os
import sys
class musci_info(object):
music_name = ''
music_url = []
music_hot = ''
def __init__(self, name, url, hot):
self.music_name = name
self.music_url = url
self.music_hot = hot
def __str__(self):
str = "歌曲名:{}\n歌曲地址:1、{}\t2、{}\t\t热度值:{}".format(self.music_name, self.music_url[0], self.music_url[1],
self.music_hot)
return str
class music(object):
def __init__(self, search_name):
"""
初始化需要的数据内容
:param search_name: 需要查找的内容
"""
self.next_url = ''
self.url = "https://www.ytmp3.cn/?search={}".format(search_name)
self.header = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/92.0.4515.159 Safari/537.36 ",
"referer": "https://www.ytmp3.cn/down"
}
self.head_url = "https://www.ytmp3.cn/"
self.session = requests.session()
self.session.headers = self.header
def search_result(self):
"""
请求地址获取响应
:return: 响应
"""
resp = self.session.get(self.url)
return resp
def get_music_url(self):
"""
解析响应内容
:return: 歌曲下载地址,歌曲热度信息
"""
result = self.search_result()
html = etree.HTML(result.content.decode())
els = html.xpath("//div[@class = 'wq_cententser']/div[2]//li[@class='ser_8']/a/@href")
els_hot = html.xpath("//div[@class = 'wq_cententser']/div[2]//li[6]/text()")
self.next_url = html.xpath("//a[text()='下一页' and @href != '']/@href")
return els, els_hot
def get_final_music_url(self, is_download):
els, els_hot = self.get_music_url()
music_num = len(els)
if music_num <= 0:
print("查询结果个数为零,三秒后自动关闭程序")
time.sleep(3)
exit(8)
else:
print("<\t\t\t\t\t搜索结果个数为{}\t\t\t\t\t>\n\n".format(music_num))
data_list = []
while True:
for idx, el in enumerate(els, 0):
music_html_url = self.head_url + el
music_html = self.session.get(music_html_url)
final_html = etree.HTML(music_html.content.decode())
try:
music_name = final_html.xpath('//h2/text()')[0]
music_url = final_html.xpath('//label/input/@value')
except IndexError:
print("获取信息失败,跳过当前歌曲信息获取,查找下一首...")
continue
if music_url[0].find('.mp4') == -1 and music_url[1].find('.mp4') == -1:
m_info = musci_info(music_name, music_url, els_hot[idx])
try:
r = self.session.get(music_url[0])
except Exception:
print("歌曲【{}】资源不存在,跳过该歌曲".format(m_info.music_name))
continue
if is_download == 'y':
filename = 'music_downloads/{}.mp3'.format(music_name)
filename_path = 'music_downloads'
if not os.path.exists(filename_path):
os.makedirs(filename_path)
with open(filename, 'wb') as f:
f.write(r.content)
print(m_info)
data_list.append(m_info)
if self.next_url:
is_next = input("下一页(Y/N)?\n").lower()
if is_next == 'y':
self.url = self.head_url + self.next_url[0]
els, els_hot = self.get_music_url()
else:
print("程序停止")
return data_list
else:
print("当前已在最后一页,程序结束")
return data_list
if __name__ == '__main__':
if len(sys.argv) == 3:
search_info = sys.argv[1]
is_download = sys.argv[2]
else:
search_info = input("请输入需要搜索的内容:\n")
is_download = input("是否同步下载歌曲到同级目录music_downloads下(Y/N):").lower()
if is_download == 'y':
idw = ''
else:
idw = '不'
print("你搜索的内容为:{}\t\t{}同步下载歌曲\n".format(search_info, idw))
res = music(search_info).get_final_music_url(is_download)
打包
或者可以直接打包成exe可执行文件 命令:pyinstaller -F python文件路径
|