文章目录

  • 项目目标
  • 具体实现步骤
    • 完整代码
    • 运行结果

项目目标

爬取qq音乐热歌榜https://y.qq.com/n/yqq/toplist/26.html到本地文件夹

具体实现步骤

程序思路:用selenium库通过目标网页的前端获取资源地址,将地址指向的文件下载至本地
本程序的selenium要配合chrome浏览器使用,selenium使用方法可以参考Selenium2+python自动化45-18种定位方法(find_elements)

完整代码

# -*- coding: utf-8 -*-
# [url=home.php?mod=space&uid=238618]@Time[/url]    : 2019/10/21 3:46 PM
# [url=home.php?mod=space&uid=686208]@AuThor[/url]  : python-小智!!
# @FileName: qq_music.py
# @Software: IntelliJ IDEAfrom selenium import webdriver
from selenium.webdriver.chrome.options import Options
from tqdm import tqdm
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import re
import json
import requests
import osclass QqMusic:def __init__(self):# 设置 chrome 无界面化模式self.chrome_options = Options()self.chrome_options.add_argument('--headless')self.chrome_options.add_argument('--disable-gpu')chrome_driver = "C:/Users/LU/AppData/Local/Programs/Python/Python37-32/Scripts/chromedriver.exe" # 指定位置,selenium的位置self.header = {"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3","accept-language": "zh-CN,zh;q=0.9","referer": "https://y.qq.com/n/yqq/toplist/26.html","upgrade-insecure-requests": "1","user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"}self.driver = webdriver.Chrome(chrome_driver, options=self.chrome_options)def loading_music(self):self.driver.get("https://y.qq.com/n/yqq/toplist/26.html")print(self.driver.title)WebDriverWait(self.driver, 10).until(EC.presence_of_all_elements_located((By.CLASS_NAME, "songlist__songname_txt")))lists = self.driver.find_elements_by_class_name("songlist__songname_txt")pattern = re.compile(r"https://y.qq.com/n/yqq/song/(\S+).html") # 取出每首歌的具体链接for i in range(len(lists)):li = lists.__getitem__(i)a = li.find_element_by_class_name("js_song")href = a.get_attribute("href")music_name = a.get_attribute("title")m = pattern.match(href)yield m.group(1), music_namedef cut_download_url(self):"""筛选和查找下载的url:return:"""for music_url, music_name in self.loading_music():data = json.dumps({"req":{"module": "CDN.SrfCdnDispatchServer", "method": "GetCdnDispatch","param": {"guid": "3802082216", "calltype": 0, "userip": ""}},"req_0": {"module": "vkey.GetVkeyServer","method":"CgiGetVkey","param": {"guid": "3802082216","songmid": [f'{music_url}'],"songtype": [0],"uin": "0","loginflag": 1,"platform":"20"}},"comm": {"uin":0,"format":"json","ct":24,"cv":0}})url = "https://u.y.qq.com/cgi-bin/musicu.fcg?callback=getplaysongvkey3131073469569151&" \"g_tk=5381&jsonpCallback=getplaysongvkey3131073469569151&loginUin=0&hostUin=0&" \f"format=jsonp&inCharset=utf8&outCharset=utf-8¬ice=0&platform=yqq&needNewCode=0&data={data}"response = requests.get(url=f"{url}",headers=self.header)html = response.textmusic_json = html.split("(")[1].split(")")[0]music_json = json.loads(music_json)req = music_json['req']['data']sip = req["sip"][-1]purl = music_json['req_0']['data']['midurlinfo'][0]['purl']url = f"{sip}{purl}"yield url, music_nameprint(music_name)#打印歌曲名def downloading(self, url, music_name):"""开始下载:param url::param music_name::return:"""res = requests.get(f"{url}")chunk_size = 1024if not os.path.exists("qq_music"):#创建名为qq_music的文件夹os.mkdir("qq_music")fileName = re.sub('[\/:*?"<>|]','-',music_name)#去掉非法字符,用-代替非法字符with open("qq_music/"+fileName+".m4a", 'wb') as f:for data in res.iter_content(chunk_size=chunk_size):f.write(data)def run(self):downloads = [x for x in self.cut_download_url()]pbar = tqdm(total=len(downloads))#用tqdm模块实现进度条显示for num, (url, music_name) in enumerate(downloads):self.downloading(url, music_name)pbar.update()QqMusic().run()

运行结果



注:本代码只用于学习交流使用

20191022时该代码可以正常使用
参考 https://y.qq.com/n/yqq/toplist/26.html

python爬虫爬取qq音乐热歌榜的歌曲到本地相关推荐

  1. python爬虫爬取网易云热歌榜top200

    爬取网易热歌榜 爬虫小练习 import requests from lxml import etree# 热歌榜首页网址 url = 'https://music.163.com/discover/ ...

  2. Python爬虫抓取某音乐网站MP3(下载歌曲、存入Sqlite)

    Python爬虫抓取某音乐网站MP3(下载歌曲.存入Sqlite) 最近右胳膊受伤,打了石膏在家休息.为了实现之前的想法,就用左手打字.写代码,查资料完成了这个资源小爬虫.网页爬虫, 最主要的是协议分 ...

  3. Python爬取网易云热歌榜所有音乐及其热评

    获取特定歌曲热评: 首先,我们打开网易云网页版,击排行榜,然后点击左侧云音乐热歌榜,如图: 关于如何抓取指定的歌曲的热评,参考这篇文章,很详细,对小白很友好: 手把手教你用Python爬取网易云40万 ...

  4. 爬虫练习:爬取网易云音乐热歌榜全部歌曲的热门评论

    目标:爬取网易云音乐热歌榜中全部歌曲(共200首)的热门评论(每首歌有15个热门评论) 分析: 需要分两步走,第一步是定位到热歌榜单所在的资源,从而得到这热歌榜中到底有哪些歌并获得每首歌的id:第二步 ...

  5. python爬取网易云热歌榜

    Python爬取网易云音乐热歌榜歌曲,并下载到本地 找到要下载歌曲排行榜的链接,这里用的是: https://music.163.com/discover/toplist?id=3778678 #网易 ...

  6. python爬虫爬取qq空间说说_用python爬取qq空间说说

    环境:PyCharm+Chorme+MongoDB Window10 爬虫爬取数据的过程,也类似于普通用户打开网页的过程.所以当我们想要打开浏览器去获取好友空间的时候必定会要求进行登录,接着再是查看说 ...

  7. 批量爬取网易云热歌榜音乐

    import requests import re**#一.发送网络请求,访问网站** url = "https://music.163.com/discover/toplist?id=37 ...

  8. python爬虫 — 爬取豆瓣最受关注图书榜

    一个简单的爬取豆瓣最受关注图书榜的小爬虫,在爬取相关信息后,将结果保存在 mongo 中 整个流程分为以下几步: (1)构造url (2)分析网页 (3)编写程序,提取信息 解析,将分别介绍以上几步 ...

  9. 爬取QQ音乐2W歌单和50W首歌曲

    主要运用了Python中的Requests包和json包获取内容,写入到Mongodb数据库并保存,pandas用于导出数据,代码详细我最后会给出github 接口分析并爬取歌单id 我发现html源 ...

最新文章

  1. a different object with the same identifier value was already associated with the session:
  2. HDU-2476 String painter 区间DP
  3. java快速压缩文件夹_如何使用java压缩文件夹本身
  4. 2017.6.27 树上操作 思考记录
  5. hihoCoder1223 不等式
  6. JdbcTemplate 排序查询结果不一致问题
  7. Android笔记(四十七) Android中的数据存储——XML(三)SAX解析
  8. LeetCode 973. K Closest Points to Origin
  9. python保存数组到txt_np.savetxt()——将array保存到txt文件,并保持原格式
  10. R语言求和上三角矩阵
  11. 简单测试ROS里面C++ 和 python 文件获取参数格式
  12. 116.【SpringBoot和Vue结合-图书馆管理系统】
  13. [C语言]实现字符串从头尾分别输出字符的动画效果
  14. 根据字体大小得到字符串显示时的宽度(C#)
  15. 教您如何采集阿里飞猪各旅行专营店的主图及视频
  16. 云安全 | 云访问安全代理 CASB
  17. Ubuntu20.04配置好文
  18. 海思HI3518e开发板 SDK安装使用
  19. 计算机网络MTU什么意思,三招使你的网速加速-mtu值怎么设置
  20. 安徽高考录取结果自动查询脚本

热门文章

  1. overflow:auto
  2. 花千芳口出狂言说英语没用,王思聪怒怼他!在线英语培训越来越重要!
  3. PS176.PD转HDMI芯片简介以及封装
  4. Android studio的ADBWifi使用
  5. 诊断DB2 Java应用程序的性能问题
  6. 计算机面试工作计划,信息技术部面试自我介绍
  7. 一、任天堂ns (Nintendo Switch) 上手
  8. Android音视频视频基础(H264)二 SPS分析
  9. 查询某个表空间下所有的表的空间占用情况
  10. i人事CTO王景飞:i人事+计算巢,协同赋能HR业务