python爬虫--10 网易云音乐
程序员文章站
2022-07-10 13:58:03
...
# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
from urllib.request import urlretrieve
from tkinter import * # init __all__ = [a,b]
import time
def download_song():
url = entry.get()
header = {
'Host': 'music.163.com',
'Referer': 'http://music.163.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
## 获取页面源代码
res = requests.get(url,headers = header).text
## 创建对象,解析网页
r = BeautifulSoup(res,'html.parser')
## 获取ID
result = r.find('ul',{'class':'f-hide'}).find_all('a') ## 找a标签
music_dict = {}
for music in result:
music_id = music.get('href').strip('/song?id=') ## 去掉'/song?id=',获取id
music_name = music.text ## .text 直接获取标签内容
music_dict[music_id] = music_name
# print(music_dict)
# 下载音乐
for song_id in music_dict:
# http://music.163.com/playlist?id=2298593931
song_url = "http://music.163.com/song/media/outer/url?id=%d.mp3"%(eval(song_id))
path = "F:\\music\\%s.mp3"%music_dict[song_id] # 下载地址
text.insert (END,"正在下载:%s.mp3"%music_dict[song_id]) ## 显示数据
text.see(END) ## 文本向下滑动
text.update() ## 更新
time.sleep(5)
urlretrieve(song_url,path) ## 真实下载
# ----------------搭建界面---------------------
## 创建窗口
root = Tk() ## 一般的标签开头均为root
## 窗口标题
root.title('网易云音乐')
## 窗口大小
root.geometry('460x410') ##小写的x
## 窗口位置
root.geometry('+200+200')
## 标签控件
label = Label(root,text = '请输入要下载的歌单URL:',font = ('行楷',10))
## 标签定位 grid网格式 pack包 place位置
label.grid()
## 输入框
entry = Entry(root,font = ('行楷',15))
## 输入框定位
entry.grid(row = 0,column = 1,stick = E)
## 列表控件
text = Listbox(root,font = ('行楷',15),width =45,height = 16)
text.grid(row = 1, columnspan = 2)
## 下载按钮
button1 = Button(root,text = '开始下载',font = ('行楷',15),command = download_song)
## 对齐 sticky = N S W E 上下左右
button1.grid(row = 2, column = 0 ,sticky = W)
## 退出按钮
button2 = Button(root,text = '退出',font = ('行楷',15))
button2.grid(row = 2,column = 1, stick = E)
# 显示窗口
root.mainloop()