当前位置: 首页 > 后端技术 > Python

python基础知识爬虫音乐资源案例

时间:2023-03-25 21:59:03 Python

python--------爬取音乐资源关于爬虫,我只是想分享一下我的经验。非常简单的爬虫希望对你有所帮助。eg:抓取的网页链接为:http://www.htqyy.com/top/hotimportrequestsimportre#url='http://www.htqyy.com/top/hot'firstpage#http://www.htqyy.com/top/hot?pageIndex=0&pageSize=20一页#http://www.htqyy.com/top/musicList/hot?pageIndex=1&pageSize=20第二页#http://www.htqyy.com/top/musicList/hot?pageIndex=2&pageSize=20三页#设置headers反爬headers={"User-Agent":"Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/79.0.3945.88Safari/537.36","Referer":"http://www.htqyy.com/top"}songName=[]songnId=[]抓取范围内i的两页资源(0,2):url="http://www.htqyy.com/top/hot?pageIndex="+str(i)+"&pageSize=20"req=requests.get(url=url,headers=headers)content=req.textpat1=r'title="(.*?)"sid'#在内容中重复使用正则匹配的歌曲名称pat2=r'sid="(.*?)"'#Songidname=re.findall(pat1,content)#常规fiadall获取列表id=re.findall(pat2,content)songName.extend(name)#将歌曲名称添加到songName列表中sonongId.extend(id)print(songName)#测试歌曲名称print(songnId)#遍历歌曲id得到歌曲id然后拼接歌曲中的urlforiinrange(0,len(songnId)):songurl="http://f2.htqyy.com/play7/"+songnId[i]+"/mp3/1"songnname=songName[i]data=requests.get(songurl).content#以字节形式打印("Downloading",i+1,"First")withopen("D:\\Music\\{}.mp3".format(songName[i]),"wb")asfw:#下载并保存fw.write(数据)效果截图如下(我只爬了几首歌曲。。。如果你想爬更多的歌曲,只需要运行更长的时间就可以了)