python爬取网易云音乐热歌榜实例代码


Posted in Python onAugust 07, 2020

首先找到要下载的歌曲排行榜的链接,这里用的是:

https://music.163.com/discover/toplist?id=3778678

然后更改你要保存的目录,目录要先建立好文件夹,例如我的是保存在D盘-360下载-网易云热歌榜文件夹内,就可以完成下载。

如果文件夹没有提前建好,会报错[Errno 2] No such file or directory。

代码实现:

from urllib import request
from bs4 import BeautifulSoup
import re
import requests
import time


class Music(object):
  def __init__(self, baseurl, path):
    head = {
      "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
      }
    self.baseurl = baseurl
    self.headers = head
    self.path = path


  def main(self):
    html = self.askurl()
    bs4 = self.analysis(html)
    name1 = self.matching(bs4)
    self.save(name1)


  def askurl(self):
    req = request.Request(url=self.baseurl, headers=self.headers)
    response = request.urlopen(req)
    html = response.read().decode("utf-8")
    return html


  def analysis(self, html):
    soup = BeautifulSoup(html, "html.parser")
    bs4 = soup.find_all("textarea")
    bs4 = str(bs4)
    return bs4


  def matching(self, bs4):
  	rule0 = re.compile(r'"name":"(.*?)","tns":[],"alias":[]')
    name0 = re.findall(rule0, bs4)
    str = ""
    for i in name0:
      str = str + "," + i
    str = str.replace("\xa0", " ")
    rule1 = re.compile(r'jpg,(.*?),(.*?)","id":(\d*)')
    name1 = re.findall(rule1, str)
    return name1


  def save(self, name1):
    for j in name1:
      print("正在下载:" + j[1] + " - " + j[0] + "...")
      url = "http://music.163.com/song/media/outer/url?id=" + j[2]
      content = requests.get(url=url, headers=self.headers).content
      with open(self.path + j[1] + " - " + j[0] + ".mp3", "wb") as f:
        f.write(content)
      print(j[1] + " - " + j[0] + "下载完毕。\n")
      time.sleep(0.5)
    return


if __name__ == "__main__":
  baseurl = "https://music.163.com/discover/toplist?id=3778678" # 要爬取的热歌榜链接
  path = "D:/360下载/网易云热歌榜/" # 保存的文件目录
  demo0 = Music(baseurl, path)
  demo0.main()
  print("下载完毕")

内容扩展:

Python3实战之爬虫抓取网易云音乐的热门评论

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re
import urllib.request
import urllib.error
import urllib.parse
import json



def get_all_hotSong(): #获取热歌榜所有歌曲名称和id
 url='http://music.163.com/discover/toplist?id=3778678' #网易云云音乐热歌榜url
 html=urllib.request.urlopen(url).read().decode('utf8') #打开url
 html=str(html) #转换成str
 pat1=r'<ul class="f-hide"><li><a href="/song\?id=\d*?" rel="external nofollow" rel="external nofollow" >.*</a></li></ul>' #进行第一次筛选的正则表达式
 result=re.compile(pat1).findall(html) #用正则表达式进行筛选
 result=result[0] #获取tuple的第一个元素

 pat2=r'<li><a href="/song\?id=\d*?" rel="external nofollow" rel="external nofollow" >(.*?)</a></li>' #进行歌名筛选的正则表达式
 pat3=r'<li><a href="/song\?id=(\d*?)" rel="external nofollow" >.*?</a></li>' #进行歌ID筛选的正则表达式
 hot_song_name=re.compile(pat2).findall(result) #获取所有热门歌曲名称
 hot_song_id=re.compile(pat3).findall(result) #获取所有热门歌曲对应的Id

 return hot_song_name,hot_song_id

def get_hotComments(hot_song_name,hot_song_id):
 url='http://music.163.com/weapi/v1/resource/comments/R_SO_4_' + hot_song_id + '?csrf_token=' #歌评url
 header={ #请求头部
 'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
 #post请求表单数据
 data={'params':'zC7fzWBKxxsm6TZ3PiRjd056g9iGHtbtc8vjTpBXshKIboaPnUyAXKze+KNi9QiEz/IieyRnZfNztp7yvTFyBXOlVQP/JdYNZw2+GRQDg7grOR2ZjroqoOU2z0TNhy+qDHKSV8ZXOnxUF93w3DA51ADDQHB0IngL+v6N8KthdVZeZBe0d3EsUFS8ZJltNRUJ','encSecKey':'4801507e42c326dfc6b50539395a4fe417594f7cf122cf3d061d1447372ba3aa804541a8ae3b3811c081eb0f2b71827850af59af411a10a1795f7a16a5189d163bc9f67b3d1907f5e6fac652f7ef66e5a1f12d6949be851fcf4f39a0c2379580a040dc53b306d5c807bf313cc0e8f39bf7d35de691c497cda1d436b808549acc'}
 postdata=urllib.parse.urlencode(data).encode('utf8') #进行编码
 request=urllib.request.Request(url,headers=header,data=postdata)
 reponse=urllib.request.urlopen(request).read().decode('utf8')
 json_dict=json.loads(reponse) #获取json
 hot_commit=json_dict['hotComments'] #获取json中的热门评论


 num=0
 fhandle=open('./song_comments','a') #写入文件
 fhandle.write(hot_song_name+':'+'\n')

 for item in hot_commit:
 num+=1
 fhandle.write(str(num)+'.'+item['content']+'\n')
 fhandle.write('\n==============================================\n\n')
 fhandle.close()




hot_song_name,hot_song_id=get_all_hotSong() #获取热歌榜所有歌曲名称和id

num=0
while num < len(hot_song_name): #保存所有热歌榜中的热评
 print('正在抓取第%d首歌曲热评...'%(num+1))
 get_hotComments(hot_song_name[num],hot_song_id[num])
 print('第%d首歌曲热评抓取成功'%(num+1))
 num+=1

以上就是python爬取网易云音乐热歌榜实例代码的详细内容,更多关于python爬取网易云音乐热歌榜的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
深入理解Python 代码优化详解
Oct 27 Python
python 中split 和 strip的实例详解
Jul 12 Python
Python实现的径向基(RBF)神经网络示例
Feb 06 Python
python读写LMDB文件的方法
Jul 02 Python
python导入pandas具体步骤方法
Jun 23 Python
python挖矿算力测试程序详解
Jul 03 Python
python用线性回归预测股票价格的实现代码
Sep 04 Python
Python3常用内置方法代码实例
Nov 18 Python
Tensorflow 多线程与多进程数据加载实例
Feb 05 Python
Python图像处理二值化方法实例汇总
Jul 24 Python
浅谈Python __init__.py的作用
Oct 28 Python
使用Python解决图表与画布的间距问题
Apr 11 Python
Python变量格式化输出实现原理解析
Aug 06 #Python
Python实现Canny及Hough算法代码实例解析
Aug 06 #Python
vscode调试django项目的方法
Aug 06 #Python
Python如何使用input函数获取输入
Aug 06 #Python
Python map及filter函数使用方法解析
Aug 06 #Python
python学习笔记之多进程
Aug 06 #Python
Selenium alert 弹窗处理的示例代码
Aug 06 #Python
You might like
《逃离塔科夫》——“萌新劝退,老手自嗨”的硬核FPS游戏
2020/04/03 其他游戏
php基础知识:控制结构
2006/12/13 PHP
php 特殊字符处理函数
2008/09/05 PHP
关于PHPDocument 代码注释规范的总结
2013/06/25 PHP
Yii2中SqlDataProvider用法示例
2016/09/22 PHP
Ajax执行顺序流程及回调问题分析
2012/12/10 Javascript
JSONP跨域的原理解析及其实现介绍
2014/03/22 Javascript
jQuery源码解读之removeAttr()方法分析
2015/02/20 Javascript
jQuery超酷平面式时钟效果代码分享
2020/03/30 Javascript
js中json处理总结之JSON.parse
2016/10/14 Javascript
JS使用正则截取两个字符串之间的字符串实现方法详解
2017/01/06 Javascript
通过js动态创建标签,并设置属性方法
2018/02/24 Javascript
使用Vuex实现一个笔记应用的方法
2018/03/13 Javascript
vue之浏览器存储方法封装实例
2018/03/15 Javascript
JS获取当前时间的年月日时分秒及时间的格式化的方法
2019/12/18 Javascript
javascript实现评分功能
2020/06/24 Javascript
[40:55]DOTA2上海特级锦标赛主赛事日 - 2 败者组第二轮#4Newbee VS Fnatic
2016/03/03 DOTA
[56:24]DOTA2上海特级锦标赛主赛事日 - 3 胜者组第二轮#1Liquid VS MVP.Phx第二局
2016/03/04 DOTA
对json字符串与python字符串的不同之处详解
2018/12/19 Python
python用for循环求和的方法总结
2019/07/08 Python
Python Collatz序列实现过程解析
2019/10/12 Python
使用python绘制温度变化雷达图
2019/10/18 Python
HTML5 canvas绘制的玫瑰花效果
2014/05/29 HTML / CSS
html5摇一摇代码优化包括DeviceMotionEvent等等
2014/09/01 HTML / CSS
Vans(范斯)德国官网:美国南加州的原创极限运动潮牌
2017/05/02 全球购物
财经学院自荐信范文
2014/02/02 职场文书
小学生倡议书范文
2014/05/13 职场文书
个人综合鉴定材料
2014/05/23 职场文书
土木工程求职信
2014/05/29 职场文书
教师自我剖析材料(群众路线)
2014/09/29 职场文书
大连导游词
2015/02/12 职场文书
狂人日记读书笔记
2015/06/30 职场文书
保护环境建议书作文500字
2015/09/14 职场文书
《攀登者》:“海拔8000米以上,你不能指望任何人”
2019/11/25 职场文书
Qt自定义Plot实现曲线绘制的详细过程
2021/11/02 Python
Java存储没有重复元素的数组
2022/04/29 Java/Android