cgl4134 发表于 2022-3-16 18:51

Python脚本批量下载音乐

一个简单的网页歌曲批量下载脚本,初学python,内容比较基础~

import requests
import re

import urllib.request
from bs4 import BeautifulSoup

response = urllib.request.urlopen("https://www.9ku.com/douyin/shenqu.htm")
content =response.read().decode('utf8')
soup = BeautifulSoup(content,"html.parser")
# l1 =soup.select('a')
# print(len(l1))
l2 =soup.find_all('a', {'href': re.compile('/play/'),'target':'_1'})
print("共扫描到"+str(len(l2))+"首歌曲,准备下载...")

i=0


def get_music_url(purl):
    """获取下载链接"""
    r = requests.get(purl)
    soup = BeautifulSoup(r.text, "lxml")

    try:
      surl = soup.find('a', {'style':'display:none'})['href']
      stitle = soup.find('li', text=re.compile('mp3下载,')).text
      sname = stitle
      returnsurl,sname
    except Exception as e:
      print(e)
      print(purl)

def download_music(sname, surl):
   """下载音乐"""
   response = requests.get(surl)
   content = response.content
   save_file(sname+'.mp3', content)
   print("保存成功:"+sname+'.mp3')


def save_file(filename, content):
   """保存音乐"""
   with open(file=filename, mode="wb") as f:
       f.write(content)

for sno in l2:
    # print("https://www.9ku.com" + sno["href"])
    purl = "https://www.9ku.com" + sno["href"].replace('play','down')
    try:
      surl,sname = get_music_url(purl)
      download_music(sname,surl)
      i=i+1
      print(i)
    except Exception as e:
      print(e)





cgl4134 发表于 2022-3-22 22:20

拾丶念 发表于 2022-3-18 19:04
bs4那个是什么?

导入python的HTML解析模块,实现html页面元素定位取值

zpolar 发表于 2022-3-17 12:26

音乐下载网站+1

yangfan512 发表于 2022-3-17 13:33

学学PYTHON

L__ 发表于 2022-3-17 13:42

谢谢分享

L__ 发表于 2022-3-17 13:53

谢谢分享

minblack3 发表于 2022-3-18 14:56

感谢楼主,这下下载音乐就方便多了

lindab701 发表于 2022-3-18 17:25

谢谢楼主!!!

拾丶念 发表于 2022-3-18 19:04

bs4那个是什么?

诡诈 发表于 2022-3-18 19:13

学学PYTHON

kc1763 发表于 2022-3-21 21:53

写的好好
页: [1] 2
查看完整版本: Python脚本批量下载音乐