前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python爬取酷狗音乐TOP500

Python爬取酷狗音乐TOP500

作者头像
andrew_a
发布2019-07-30 14:34:41
1.6K1
发布2019-07-30 14:34:41
举报

好久没发过爬虫了,发这个主要是因为我女朋友说本地没有歌,有的歌还是VIP下载不了,平时听歌还得用流量。所以就想着看能直接把所有的歌曲直接拿下来。就去看了酷狗的主页面。想直接拿到TOP500.因为没找到怎么去下载,然后就在网上找了一下,找到了一个根据hash拼接url,下载歌曲。,只要找到hash值就啥都解决了。

看了之后发现还不是特别难弄,所以就直接趴下来了。

上面是网址,

改变数字就可以实现翻页,所以这个不能翻页的问题解决了。然后就是老套路按F12查看找network.

往下翻,发现这些都有注释,那就更好办了。

解析这个数据,拿出来hash值和filename,歌词lyric。

也没什么要说的了,直接贴代码

代码语言:javascript
复制
import requests
from lxml import etree
import json
import re
import os

class kugou():

    def startkugou(self):
        for i in range(23, 24):
            print(i)
            res = requests.get('https://www.kugou.com/yy/rank/home/%s-8888.html?from=rank' % str(i))
            self.get_song(res)

    def get_song(self, res):
        html = etree.HTML(res.content.decode('utf8'))
        content = html.xpath('//script[10]')
        content2 = content[0].text
        # 解析出json列表,类型是str
        content1 = content2.split('global.features =')[1].split('(function()')[0].strip()[0:-1]
        try:
            # 转换成json数据
            content = json.loads(content1)
            for i in range(len(content)):
                hash = content[i]["Hash"]
                file_name = content[i]["FileName"]
                hash_url = "http://www.kugou.com/yy/index.php?r=play/getdata&hash=" + hash
                hash_content = requests.get(hash_url)
                play_url = ''.join(re.findall('"play_url":"(.*?)"', hash_content.text))
                lyrics = ''.join(re.findall('"lyrics":"(.*?)"', hash_content.text))
                real_download_url = play_url.replace("\\", "")
                try:
                    # if os.path.exists('kugou/' + file_name + '.txt'):
                    #     print(file_name + " 歌词已经存在")
                    #     # continue
                    # else:
                    with open('kugou/' + file_name + '.txt', 'w', encoding='utf8')as f:
                        f.write(lyrics.encode('utf8').decode('unicode_escape'))
                    print(file_name + "歌词已下载完成!")
                    # if os.path.exists('kugou/' + file_name + '.mp3'):
                    #     print(file_name+" 歌曲已经存在")
                    #     # continue
                    # else:
                    with open('kugou/' + file_name + ".mp3", "wb")as fp:
                        fp.write(requests.get(real_download_url).content)
                    print(file_name + "歌曲已下载完成!")
                except OSError as e:
                    print("出现异常" + file_name)
                    file_name = self.validateTitle(file_name)
                    # if os.path.exists('kugou/' + file_name + '.txt'):
                    #     print(file_name + " 歌词已经存在")
                    #     # continue
                    # else:
                    with open('kugou/' + file_name + '.txt', 'w', encoding='utf8')as f:
                        f.write(lyrics.encode('utf8').decode('unicode_escape'))
                    print(file_name + "歌词已下载完成!")
                    # if os.path.exists('kugou/' + file_name + '.mp3'):
                    #     print(file_name + " 歌曲已经存在")
                    #     # continue
                    # else:
                    with open('kugou/' + file_name + ".mp3", "wb")as fp:
                        fp.write(requests.get(real_download_url).content)
                    print(file_name + "歌曲已下载完成!")


        except json.decoder.JSONDecodeError as e:
            print(e)
            print(content2)
            content1 = content2.split('global.features =')[1].strip().split('(function() {')[0].strip()
            content1 = content1[0:-1]
            print(content1)

    def validateTitle(self, file_name):
        """ 将 title 名字 规则化
        :param title: title name 字符串
        :return: 文件命名支持的字符串        """
        rstr = r"[\=\(\)\,\/\\\:\*\?\"\<\>\|\' ']"  # '= ( ) , / \ : * ? " < > |  '   还有空格
        new_title = re.sub(rstr, "_", file_name)  # 替换为下划线
        return new_title

if __name__ == '__main__':
    kugou().startkugou()

代码基本都有注释,有问题可以留言,谢谢!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-12-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python爬虫scrapy 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档