Download Netease cloud music 10W + music library with Python

Watch the corner. 2020-11-09 11:36:36
download netease cloud music 10w


If you listen to music a lot , I can't get around Netease cloud , As a kind of emotional music App, I also like Netease cloud . Although it is now all 5G Times , We have more than enough mobile phone traffic , But playing online is not as reliable as storing music files locally , We'll use it today Python One click download Netease cloud music library .

First, look at the final effect .

Actually, it's not hard to download music , You just need to get the address of the music file, you can download it directly by reading the file stream . So the problem is how to get the playing address of music file .

List analysis

We can open the Netease cloud ranking list  https://music.163.com/#/discover/toplist?id=19723756, After careful analysis, we find that the left column of the page is full of leaderboards , Each list corresponds to a different list ID, Specifically ID How much is the , Open the developer tool directly to see .

From the picture above, we can see that the list is placed in a  class='f-cb'  Of  ul  In the list , So just get it  ul  List  li  Labels can be . And for each  li  The label is , Its  data-res-id  Property is the list id, And the list name belongs to the  li  Label under  div  in  class='name'  Of  p  Label under  a  Content of the label . So we got  li  After the collection of tags , Traverse the collection and take out the list in turn id And the list name .

So we have the following function , Get all the lists , The function returns a dictionary ,key by The list id, Value is the list name .

url = 'https://music.163.com/discover/toplist'
hd = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'
}
def get_topic_ids():
    r = requests.get(url, headers=hd)
    html = etree.HTML(r.text)
    nodes = html.xpath("//ul[@class='f-cb']/li")
    logger.info('{}  {}'.format(' The list  ID', ' List name '))
    ans = dict()
    for node in nodes:
        id = node.xpath('./@data-res-id')[0]
        name = node.xpath("./div/p[@class='name']/a/text()")[0]
        ans[id] = name
        logger.info('{}  {}'.format(id, name))
    return ans

Song analysis

We've got all the list data above , So for a single list , I want to get all the songs under it .

The analysis page is known , The list of songs is in one  table  Medium , But by  requests.get(url,headers=hd)  Method to get the returned page text content , It seems that I can't get  table  Elemental . So we output its return value and do a careful analysis , Find that the song is in  class="f-hide"  Of  ul  In the label . Similar to getting a list , It's also necessary to get all of it first  li  label , Then get the songs one by one id And songs name That's all right. .

def get_topic_songs(topic_id, topic_name):
    params = {
        'id': topic_id
    }
    r = requests.get(url, params=params, headers=hd)
    html = etree.HTML(r.text)
    nodes = html.xpath("//ul[@class='f-hide']/li")
    ans = dict()
    logger.info('{}  The list  {}  There are songs in common  {}  The first  {}'.format('*' * 10, topic_name, len(nodes), '*' * 10))
    for node in nodes:
        id = node.xpath('./a/@href')[0].split('=')[1]
        name = node.xpath('./a/text()')[0]
        ans[id] = name
        logger.info('{}  {}'.format(id, name))
    return ans

Again, the function returns a dictionary ,key For the song id,value Name for the song .

Download songs

We also need a function to download songs , This function receives songs id, Then read it directly to the local as a file stream .

def down_song_by_song_id_name(id, name):
    if not os.path.exists(download_dir):
        os.mkdir(download_dir)
    url = 'http://music.163.com/song/media/outer/url?id={}.mp3'
    r = requests.get(url.format(id), headers=hd)
    is_fail = False
    try:
        with open(download_dir + name + '.mp3', 'wb') as f:
            f.write(r.content)
    except:
        is_fail = True
        logger.info("%s  Download error " % name)
    if (not is_fail):
        logger.info("%s  Download complete " % name)

Finally, all the operations are combined into main Function , As an entry function of a program .

def main():
    ids = get_topic_ids()
    while True:
        print('')
        logger.info(' Input  Q  Exit procedure ')
        logger.info(' Input  A  Download all the list songs ')
        logger.info(' Enter the list  Id  Download the current list songs ')
        id = input(' Please enter :')
        if str(id) == 'Q':
            break
        elif str(id) == 'A':
            for id in ids:
                down_song_by_topic_id(id, ids[id])
        else:
            print('')
            ans = get_topic_songs(id, ids[id])
            print('')
            logger.info(' Input  Q  Exit procedure ')
            logger.info(' Input  A  Download all songs ')
            logger.info(' Enter the song  Id  Download the current song ')
            id = input(' Please enter :')
            if str(id) == 'Q':
                break
            elif id == 'A':
                down_song_by_topic_id(id, ans[id])
            else:
                down_song_by_song_id_name(id, ans[id])
if __name__ == "__main__":
    main()

summary

Today, we use Netease cloud as the data source to download music files , The download operation is the simplest , The trouble is to analyze the list id And get the list of songs under the list , But the list of songs under the list is much more than 10 strip , And we get the function of the song  get_topic_songs  You can only get it at a time 10 Songs , This is because we are not in  headers  add to  cookie  As a result of , Because all the songs will be displayed only after logging in . Partners can log in to their accounts and add  cookie  Try it .

Be careful : If you're looking for python Well paid jobs . I suggest you write more about real enterprise projects and accumulate experience . Or you won't find a job , Of course, a lot of people have never been in a business , How can there be project experience ? So you have to find more enterprise projects and practice more . If you're lazy and don't want to find , You can also enter my Python Circle of communication :1156465813. There are some real enterprise project cases that I have written before in the group file . You can take it to study , If you don't understand, you can find me in your skirt , I'll answer you patiently when I have time .

 

The following is useless , For this blog to be crawled by search engines
(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)
python What is it Zero basis to learn python How long will it take? python Why is it called a reptile
python Novice reptile tutorial python Crawler universal code python How do reptiles make money
python Basic course Web crawler python python Classic examples of reptiles
python Reptiles
(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)(* ̄︶ ̄)
The above is useless , For this blog to be crawled by search engines

版权声明
本文为[Watch the corner.]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database