日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python爬虫获取网易云音乐歌单

發布時間:2023/12/9 python 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python爬虫获取网易云音乐歌单 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

代碼如下:?

from bs4 import BeautifulSoup import requests import timeheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' }for i in range(0, 1330, 35):print(i)time.sleep(2)url = 'https://music.163.com/discover/playlist/?cat=歐美&order=hot&limit=35&offset=' + str(i)response = requests.get(url=url, headers=headers)html = response.textsoup = BeautifulSoup(html, 'html.parser')# 獲取包含歌單詳情頁網址的標簽ids = soup.select('.dec a')# 獲取包含歌單索引頁信息的標簽lis = soup.select('#m-pl-container li')print(len(lis))for j in range(len(lis)):# 獲取歌單詳情頁地址url = ids[j]['href']# 獲取歌單標題title = ids[j]['title']# 獲取歌單播放量play = lis[j].select('.nb')[0].get_text()# 獲取歌單貢獻者名字user = lis[j].select('p')[1].select('a')[0].get_text()# 輸出歌單索引頁信息print(url, title, play, user)# 將信息寫入CSV文件中with open('playlist.csv', 'a+', encoding='utf-8-sig') as f:f.write(url + ',' + title + ',' + play + ',' + user + '\n')

獲取歌單信息如下:?

二次代碼如下:?

from bs4 import BeautifulSoup import pandas as pd import requests import timedf = pd.read_csv('playlist.csv', header=None, error_bad_lines=False, names=['url', 'title', 'play', 'user'])headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' }for i in df['url']:time.sleep(2)url = 'https://music.163.com' + iresponse = requests.get(url=url, headers=headers)html = response.textsoup = BeautifulSoup(html, 'html.parser')# 獲取歌單標題title = soup.select('h2')[0].get_text().replace(',', ',')# 獲取標簽tags = []tags_message = soup.select('.u-tag i')for p in tags_message:tags.append(p.get_text())# 對標簽進行格式化if len(tags) > 1:tag = '-'.join(tags)else:tag = tags[0]# 獲取歌單介紹if soup.select('#album-desc-more'):text = soup.select('#album-desc-more')[0].get_text().replace('\n', '').replace(',', ',')else:text = '無'# 獲取歌單收藏量collection = soup.select('#content-operation i')[1].get_text().replace('(', '').replace(')', '')# 歌單播放量play = soup.select('.s-fc6')[0].get_text()# 歌單內歌曲數songs = soup.select('#playlist-track-count')[0].get_text()# 歌單評論數comments = soup.select('#cnt_comment_count')[0].get_text()# 輸出歌單詳情頁信息print(title, tag, text, collection, play, songs, comments)# 將詳情頁信息寫入CSV文件中with open('music_message.csv', 'a+', encoding='utf-8-sig') as f:f.write(title + ',' + tag + ',' + text + ',' + collection + ',' + play + ',' + songs + ',' + comments + '\n')# 獲取歌單內歌曲名稱li = soup.select('.f-hide li a')for j in li:with open('music_name.csv', 'a+', encoding='utf-8-sig') as f:f.write(j.get_text() + '\n')

?最后獲取的詳情頁如下:

總結

以上是生活随笔為你收集整理的python爬虫获取网易云音乐歌单的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。