小白教程

 找回密码
 立即注册
小白教程 首页 Python技术文章 查看内容

Python爬虫爬取网易云音乐的方法

发布者: 小白教程

前言
最近网易的音乐我听不到很多,只是碰巧看了很多教程。我跟进了一下,学到了一点,我已经汇编了一下。我想优化它,但我发现问题仍然有点复杂。最后,我找到了一个快捷方式,提供了简单性的方式!
首先,让我们来谈谈准备工作:
Python:需要基本的Python语法基础
请求:专业用于请求处理、请求库学习文档的中文版
lxml:实际上,你可以使用python自己的正则表达式库re,但是为了更容易开始,使用lxml中的树来定位和抓取网页数据。
Re: python正则表达式处理
Json: python的Json处理库
然后,假设你现在知道下载链接是这样的:

http://music.163.com/song/media/outer/url?id='

Id就是这首歌的Id !
所以,现在我们的爬虫的主要工作就是找到这个id,当然,为了更好的保存它,我们也一定要找到这个歌名!
所以现在就是找到我们需要抓取的网站链接了!我分析了一下,大概有以下三种类型:

#歌曲清单
music_list = 'https://music.163.com/#/playlist?id=2412826586' 
#歌手排行榜
artist_list = 'https://music.163.com/#/artist?id=8325'
#搜索列表 
search_list = 'https://music.163.com/#/search/m/?order=hot&cat=全部&limit=435&offset=435&s=梁静茹' 

如果你只是想下载一首歌,如《惊魂-勇气:https://music.163.com/#/song?id=254485》,那么你可以直接用浏览器打开http://music.163。com/song/media/outer/url吗?Id =254485很好,不用爬!
下载歌词
如果你想下载歌词,也很简单,通过界面,你可以有歌曲的id:

url = 'http://music.163.com/api/song/lyric?id={}&lv=-1&kv=-1&tv=-1'.format(song_id)

返回的json数据

{
    sgc: true,
    sfy: false,
    qfy: false,
    lrc:
    {
        version: 7,
        lyric: "[00:39.070]开了窗 等待天亮\n[00:46.160]看这城市 悄悄的 熄了光\n[00:51.850]听风的方向\n[00:55.090]这一刻 是否和我一样\n[00:58.730]孤单的飞翔\n[01:02.300]模糊了眼眶\n[01:07.760]广播里 那首歌曲\n[01:14.830]重复当时 那条街那个你\n[01:20.410]相同的桌椅\n[01:23.740]不用言语 就会有默契\n[01:27.470]这份亲密\n[01:30.560]那么熟悉\n[01:33.850]在爱里 等着你\n[01:37.480]被你疼惜 有种暖意\n[01:41.090]在梦里 全是你\n[01:43.920]不要再迟疑 把我抱紧"
    },
    klyric:
    {
        version: 0,
        lyric: null
    },
    tlyric:
    {
        version: 0,
        lyric: null
    },
    code: 200
}

python模拟浏览器
使用selenium+phantomjs无界面浏览器,两者的结合实际上是直接操作浏览器,可以在JavaScript渲染后得到页面数据。
缺点
因为它是一个非界面浏览器,所以这个解决方案效率非常低,不推荐用于大规模爬行。
对于源代码中不存在的异步请求和数据,不能同时捕获数据。
搜索的歌曲成为播放列表
例如,如果你想下载某歌手的所有音乐,使用手机云音乐搜索,然后保存到一个新的播放列表,就这样!
总结
使用python,它必须简单。我认为复杂的事情应该做的越少越好,如果你能采取一些技巧,这篇文章不使用selenium+phantomjs来练习。
注:本文仅用于技术交流,请勿用于商业用途~我将不对任何违规行为负责。
所有代码
这是非常简单的100行代码!!!

import os
import re
import json
import requests
from lxml import etree


def download_songs(url=None):
    if url is None:
        url = 'https://music.163.com/#/playlist?id=2384642500'

    url = url.replace('/#', '').replace('https', 'http')  # 对字符串进行去空格和转协议处理
    # 网易云音乐外链url接口:http://music.163.com/song/media/outer/url?id=xxxx
    out_link = 'http://music.163.com/song/media/outer/url?id='
    # 请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
        'Referer': 'https://music.163.com/',
        'Host': 'music.163.com'
    }
    # 请求页面的源码
    res = requests.get(url=url, headers=headers).text

    tree = etree.HTML(res)
    # 音乐列表
    song_list = tree.xpath('//ul[@class="f-hide"]/li/a')
    # 如果是歌手页面
    artist_name_tree = tree.xpath('//h2[@id="artist-name"]/text()')
    artist_name = str(artist_name_tree[0]) if artist_name_tree else None

    # 如果是歌单页面:
    #song_list_tree = tree.xpath('//*[@id="m-playlist"]/div[1]/div/div/div[2]/div[2]/div/div[1]/table/tbody')
    song_list_name_tree = tree.xpath('//h2[contains(@class,"f-ff2")]/text()')
    song_list_name = str(song_list_name_tree[0]) if song_list_name_tree else None

    # 设置音乐下载的文件夹为歌手名字或歌单名
    folder = './' + artist_name if artist_name else './' + song_list_name

    if not os.path.exists(folder):
        os.mkdir(folder)

    for i, s in enumerate(song_list):
        href = str(s.xpath('./@href')[0])
        song_id = href.split('=')[-1]
        src = out_link + song_id  # 拼接获取音乐真实的src资源值
        title = str(s.xpath('./text()')[0])  # 音乐的名字
        filename = title + '.mp3'
        filepath = folder + '/' + filename
        print('开始下载第{}首音乐:{}\n'.format(i + 1, filename))

        try:  # 下载音乐
            #下载歌词
            #download_lyric(title, song_id)

            data = requests.get(src).content  # 音乐的二进制数据

            with open(filepath, 'wb') as f:
                f.write(data)
        except Exception as e:
            print(e)

    print('{}首全部歌曲已经下载完毕!'.format(len(song_list)))


def download_lyric(song_name, song_id):
    url = 'http://music.163.com/api/song/lyric?id={}&lv=-1&kv=-1&tv=-1'.format(song_id)
    # 请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
        'Referer': 'https://music.163.com/',
        'Host': 'music.163.com'
        # 'Origin': 'https://music.163.com'
    }
    # 请求页面的源码
    res = requests.get(url=url, headers=headers).text
    json_obj = json.loads(res)
    lyric = json_obj['lrc']['lyric']
    reg = re.compile(r'\[.*\]')
    lrc_text = re.sub(reg, '', lyric).strip()

    print(song_name, lrc_text)




if __name__ == '__main__':
    #music_list = 'https://music.163.com/#/playlist?id=2384642500' #歌曲清单
    music_list = 'https://music.163.com/#/artist?id=8325' #歌手排行榜
    # music_list = 'https://music.163.com/#/search/m/?order=hot&cat=全部&limit=435&offset=435&s=梁静茹' #搜索列表
    download_songs(music_list)




Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-19 12:10 , Processed in 0.015695 second(s), 15 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部