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模拟鼠标拖动操作的方法
Mar 11 Python
Python+django实现文件上传
Jan 17 Python
Python模块包中__init__.py文件功能分析
Jun 14 Python
详解常用查找数据结构及算法(Python实现)
Dec 09 Python
Python实现将数据库一键导出为Excel表格的实例
Dec 30 Python
利用numpy+matplotlib绘图的基本操作教程
May 03 Python
对Python w和w+权限的区别详解
Jan 23 Python
Python实现查找二叉搜索树第k大的节点功能示例
Jan 24 Python
Python实现最常见加密方式详解
Jul 13 Python
基于python3.7利用Motor来异步读写Mongodb提高效率(推荐)
Apr 29 Python
对python pandas中 inplace 参数的理解
Jun 27 Python
彻底解决Python包下载慢问题
Nov 15 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
PHP clearstatcache()函数详解
2010/03/02 PHP
Zend Framework教程之连接数据库并执行增删查的方法(附demo源码下载)
2016/03/21 PHP
调用WordPress函数统计文章访问量及PHP原生计数器的实现
2016/03/21 PHP
JS解析XML的实现代码
2009/11/12 Javascript
php对mongodb的扩展(初识如故)
2012/11/11 Javascript
Jquery选中或取消radio示例
2013/09/29 Javascript
javascript创建和存储cookie示例
2014/01/07 Javascript
Javascript前端UI框架Kit使用指南之kitjs的对话框组件
2014/11/28 Javascript
jQuery向后台传入json格式数据的方法
2015/02/13 Javascript
第一次接触神奇的Bootstrap导航条
2016/08/09 Javascript
jQuery特殊符号转义的实现
2016/11/30 Javascript
HTML页面定时跳转方法解析(2种任选)
2016/12/22 Javascript
Layui table 组件的使用之初始化加载数据、数据刷新表格、传参数
2017/09/11 Javascript
20行JS代码实现粘贴板复制功能
2018/02/06 Javascript
vue 使用html2canvas将DOM转化为图片的方法
2018/09/11 Javascript
JavaScript ES6箭头函数使用指南
2018/12/30 Javascript
Vue.js中的extend绑定节点并显示的方法
2019/06/20 Javascript
[57:53]DOTA2上海特级锦标赛主赛事日 - 2 败者组第二轮#3OG VS VP
2016/03/03 DOTA
Python实现简单的代理服务器
2015/07/25 Python
python批量导入数据进Elasticsearch的实例
2018/05/30 Python
关于Python3 类方法、静态方法新解
2019/08/30 Python
Python爬取爱奇艺电影信息代码实例
2019/11/26 Python
python实现时间序列自相关图(acf)、偏自相关图(pacf)教程
2020/06/03 Python
Python执行时间的几种计算方法
2020/07/31 Python
CSS3 Media Queries(响应式布局可以让你定制不同的分辨率和设备)
2013/06/06 HTML / CSS
Booking.com英国官网:全球酒店在线预订网站
2018/04/21 全球购物
俄罗斯花园种植材料批发和零售网上商店:Беккер
2019/07/22 全球购物
美国家居装饰购物网站:Amanda Lindroth
2020/03/25 全球购物
结构和类有什么异同
2012/07/16 面试题
2019年.net常见面试问题
2012/02/12 面试题
环保倡议书怎么写
2014/05/16 职场文书
党员个人对照检查材料范文
2014/09/24 职场文书
三峡导游词
2015/01/31 职场文书
2015年个人招商工作总结
2015/04/25 职场文书
PhpSpreadsheet中文文档 | Spreadsheet操作教程实例
2021/04/01 PHP
美元符号 $
2022/02/17 杂记