1. import requests
    2. import re
    3. import json
    4. import os
    5. if __name__ == '__main__':
    6. url = 'https://y.music.163.com/m/album?id=16959'
    7. songURL = '下载地址不公开'
    8. headers = {
    9. 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Mobile Safari/537.36'
    10. }
    11. response = requests.get(url=url, headers=headers)
    12. if response.status_code == 200:
    13. html = response.content.decode()
    14. # 使用正则表达式提取网易js中的json数据
    15. pattern = re.compile(r'{"Album".*}', re.I | re.M)
    16. js = pattern.findall(html)[0]
    17. json_text = json.loads(js)
    18. songs = json_text['Album']['songs']
    19. songNames = []
    20. if len(songs) > 0:
    21. for song_item in songs:
    22. dict = {}
    23. dict['id'] = songURL.format(song_item['id'])
    24. dict['songName'] = song_item['songName']
    25. songNames.append(dict)
    26. file_path = '许嵩歌曲'
    27. for song in songNames:
    28. url = song['id']
    29. response = requests.get(url=url, headers=headers)
    30. if response.status_code == 200:
    31. data = response.content
    32. try:
    33. if not os.path.exists(file_path):
    34. print('文件夹', file_path, '不存在,重新建立')
    35. os.makedirs(file_path)
    36. # 拼接图片名(包含路径)
    37. filename = '{}/{}'.format(file_path,
    38. song['songName']) + '.mp3'
    39. with open(filename, 'wb')as f:
    40. f.write(data)
    41. print('真正下载歌曲【%s】' % song['songName'])
    42. except IOError as e:
    43. print('文件操作失败:' + e)
    44. except Exception as e:
    45. print('错误:' + e)

    截屏2020-11-13 17.06.45.png