代码如下
import requests
from lxml import etree
import os
url = 'https://music.163.com/discover/toplist?id=3779629'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400'
}
data = requests.get(url=url, headers=headers)
html = etree.HTML(data.text)
music_list = html.xpath('//ul[@class="f-hide"]/li/a')
music_lis = []
for music in music_list:
music_name = music.xpath('./text()')[0]
music_id_all = music.xpath('./@href')[0]
music_id = music_id_all.split('=')[-1]
download_music = music_name + ' ' + f'http://music.163.com/song/media/outer/url?id={music_id}.mp3'
music_lis.append(download_music)
print(download_music)
for url in music_lis:
try:
url_name = url.split(' ')[0]
url_music = url.split(' ')[1]
print(f'{url_name}===>正在下载')
response_music = requests.get(url=url_music, headers=headers)
with open(f'./网易云音乐/{url_name}.mp3', 'wb') as fp:
fp.write(response_music.content)
print(f'{url_name}===>下载成功')
except:
print('============错误================')
效果如下
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ca580490d0608055b9916ef3232a913e.png)