分享网易云音乐任何歌手的歌的歌词和评论爬取,存在本地

 前提说明:

当你运行代码,会让你输入歌手编号。

拿张国荣举例,输入之后,直接运行即可,然后在本地会自动生成results文件夹,里面就是你喜欢的歌手的歌的歌词

 源码奉上

import requests
from bs4 import BeautifulSoup
import re
import json
import time
import random
import os

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3355.4 Safari/537.36',
'Referer': 'http://music.163.com',
'Host': 'music.163.com'
}


# 获取页面源码
def GetHtml(url):
    try:
        res = requests.get(url=url,headers=headers)
    except:
        return None
    return res.text


# 提取歌手歌词信息
def GetSongsInfo(url):
    print('[INFO]:Getting Songs Info...')
    html = GetHtml(url)
    soup = BeautifulSoup(html,'lxml')
    links = soup.find('ul',class_='f-hide').find_all('a')
    if len(links)<1:
        print('[Warning]:_GetSongsInfo <links> not find...')
    Info={'ID':[],'NAME':[]}
    for link in links:
        SongID = link.get('href').split('=')[-1]
        SongName = link.get_text()
        Info['ID'].append(SongID)
        Info['NAME'].append(SongName)
    return Info


def GetLyrics(SongID):
    print('[INFO]:Getting %s lyric...' % SongID)
    ApiUrl = 'http://music.163.com/api/song/lyric?id={}&lv=1&kv=1&tv=-1'.format(SongID)
    html = GetHtml(ApiUrl)
    html_json = json.loads(html)
    temp = html_json['lrc']['lyric']
    rule = re.compile(r'(.*?)', re.I | re.S | re.M)
    lyric = re.sub(rule,'',temp).strip()
    return lyric


def SaveLyrics(SongName,lyric):
    print('[INFO]: Start to Save {}...'.format(SongName))
    if not os.path.isdir('./results'):
        os.makedirs('./results')
    with open('./results/{}.txt'.format(SongName),'w',encoding='utf-8')as f:
        f.write(lyric)


def main():
    SingerId = input('Enter the Singer ID:')
    url = 'http://music.163.com/artist?id={}'.format(SingerId)
    Info = GetSongsInfo(url)
    IDs=Info['ID']
    i=0
    for ID in IDs:
        print(ID)
        lyric=GetLyrics(ID)
        SaveLyrics(Info['NAME'][i],lyric)
        i+=1
        time.sleep(random.random() * 3)
main()

网易云评论,以张国荣举例


# coding:utf-8
import json
import time
import requests
from fake_useragent import UserAgent
import random
import multiprocessing
import sys
#reload(sys)
#sys.setdefaultencoding('utf-8')

ua = UserAgent(verify_ssl=False)

song_list = [{'186453':'春夏秋冬'},{'188204':'沉默是金'},{'188175':'倩女幽魂'},{'188489':'风继续吹'},{'187374':'我'},{'186760':'风雨起时'}]
headers = {
'Origin':'https://music.163.com',
'Referer': 'https://music.163.com/song?id=26620756',
'Host': 'music.163.com',
'User-Agent': ua.random
}

def get_comments(page,ite):
# 获取评论信息
# """
    for key, values in ite.items():
        song_id = key
        song_name = values
        url = 'http://music.163.com/api/v1/resource/comments/R_SO_4_'+ song_id +'?limit=20&offset=' + str(page)
        # 使用ip代理池
        # ip_list = [IP列表]
        # proxies = get_random_ip(ip_list)
        try:
            # response = requests.get(url=url,headers=headers,proxies=proxies)
            response = requests.get(url=url, headers=headers)
        except Exception as e:
            print(page)
            print(ite)
        result = json.loads(response.text)
        items = result['comments']
        for item in items:
            # 用户名
            user_name = item['user']['nickname'].replace(',',',')
            # 用户ID
            user_id = str(item['user']['userId'])
            print(user_id)
            # 评论内容
            comment = item['content'].strip().replace('\n', '').replace(',', ',')
            print(comment)
            # 评论ID
            comment_id = str(item['commentId'])
            # 评论点赞数
            praise = str(item['likedCount'])
            # 评论时间
            date = time.localtime(int(str(item['time'])[:10]))
            date = time.strftime("%Y-%m-%d %H:%M:%S",date)




get_comments(1,song_list[0])





 

好的,下面我为您提供具体的Python代码实现,爬取网易云音乐曲信息: 首先,我们需要使用requests库向API接口发送请求,并将响应内容解析为JSON格式。这里我们以搜索关键词为"周杰伦"的曲为例: ```python import requests import json search_api = 'https://music.163.com/api/search/get/web' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3', 'Referer': 'https://music.163.com/', 'Host': 'music.163.com' } params = { 's': '周杰伦', 'type': 1, 'offset': 0, 'limit': 10 } response = requests.get(search_api, headers=headers, params=params) json_data = json.loads(response.text) ``` 接下来,我们可以根据需求解析JSON数据,获取所需要的曲信息。例如,获取第一首曲的名称和歌手: ```python song_name = json_data['result']['songs'][0]['name'] artist = json_data['result']['songs'][0]['ar'][0]['name'] print('曲名:', song_name) print('歌手:', artist) ``` 最后,我们可以使用Python的第三方库进行音乐下载和存储。这里我们以使用pydub库将下载为mp3格式并保存在本地为例: ```python from pydub import AudioSegment song_url = json_data['result']['songs'][0]['mp3Url'] song_content = requests.get(song_url).content song = AudioSegment.from_file(song_content) song.export(song_name+'.mp3', format='mp3') ``` 以上就是使用Python爬取网易云音乐曲信息的基本流程,您可以根据自己的需要进行相应的修改和扩展。另外需要注意的是,网易云音乐的API接口可能会有限制或者需要登录,所以在爬取过程中需要注意遵守相关规定,避免出现违规行为。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值