Python批量下载dj音乐脚本

一到晚上就想嗨,不想睡,这个时候就需要点音乐,于是乎找了找DJ网站,结果发现下载都要钱,作为一个不富裕的平民,笔者肯定还是舍不得的。所以搜集了这个脚本,在Python环境中运行即可。

本实例摘自互联网,请勿用于商业用途!

# -*- coding : 'UTF-8' -*-
# 'http://www.djkk.com/dance/sort/chinese_1.html'
# Author :XSX
# Python3.8 PyCharm Community Edition 2019.3.3

# 导入所有使用的模块,没有的自行pip install 库名称 进行安装
import requests
import re
import os
from lxml import etree
from GetRandomheader import Randomheader
import time

# 得到某页下所有歌曲链接
def Getsonglinks(url, headers):
    songLinks = []
    rsp = requests.get(url, headers=headers)
    rsp.encoding = rsp.apparent_encoding
    html = etree.HTML(rsp.text)
    songlinks = html.xpath('//div[@class="song layui-elip layui-col-xs12 layui-col-sm8 layui-col-md6"]/div/a/@href')
    for songlink in songlinks:
        songdata = 'http://www.djkk.com' + str(songlink)
        songLinks.append(songdata)
    print(songLinks)
    return songLinks

# 正则匹配歌曲下载地址以及歌曲名,最后新建文件夹后进行下载保存。
def GetPageText(url, headers):
    r = requests.get(url, headers=headers)
    r.encoding = r.apparent_encoding
    songurls = re.findall(r'.*songurl: "(.*)",time.*', r.text)
    songnames = re.findall(r'.*songname:"(.*)",songtype.*', r.text)
    songurl = str(songurls)[2:-2]
    songname = str(songnames)[2:-2]
    print('正在下载 》》》》》' + songname + '\n' + '------------------------------------')
    print('歌曲地址:' + songurl)
    if not os.path.exists('./DJSongs'):
        os.mkdir('./DJSongs')
    r1 = requests.get(songurl, headers=headers)
    with open('./DJSongs/' + songname + '.m4a', 'wb')as f:
        f.write(r1.content)

# 定义main函数,并调用上方封装函数运行代码。
if __name__ == '__main__':
    url1 = 'http://www.djkk.com/dance/sort/chinese_2.html'
    headers = Randomheader()
    for url in Getsonglinks(url1, headers):
        time.sleep(2)
        GetPageText(url, headers)
    print('全部下载完成!')

运行效果如下

转载请注明本文链接:http://python.doc.weixiaoline.com/68.html

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注