返回
通过Python轻松实现网易云歌单歌曲热评爬取_爬虫实战篇
闲谈
2023-09-13 08:26:48
前言
网络爬虫,这一互联网时代的利器,犹如一柄双刃剑,既可为我们探索信息海洋,也可能成为网络安全的隐患。而Python,作为一门功能强大的编程语言,凭借其丰富的库和友好的语法,为我们提供了一个构建高效爬虫的绝佳平台。本文将带领大家使用Python打造一个简单的爬虫,目标直指网易云音乐的歌单歌曲热评,旨在为您的音乐探索之旅增添一份数据驱动的洞察。
代码实现
1. 导入必要的库
import requests
from bs4 import BeautifulSoup
import pandas as pd
2. 定义网易云音乐歌单歌曲热评URL
base_url = "https://music.163.com/playlist?id={}"
song_url = "{}/songs"
comment_url = "{}?csrf_token="
3. 获取歌单信息
def get_playlist_info(playlist_id):
url = base_url.format(playlist_id)
response = requests.get(url)
soup = BeautifulSoup(response.text, "lxml")
return soup
4. 解析歌单中的歌曲信息
def get_song_info(playlist_soup):
songs = []
for song in playlist_soup.select("ul.f-hide li"):
song_id = song.get("data-res-id")
song_name = song.select_one("a").text
songs.append({"song_id": song_id, "song_name": song_name})
return songs
5. 获取歌曲热评
def get_song_comments(song_id, csrf_token):
url = comment_url.format(song_url.format(song_id), csrf_token)
response = requests.get(url)
data = response.json()
return data["comments"]
程序实战
1. 创建一个网易云音乐歌单ID列表
playlist_ids = [1842863126, 247764227, 1199761641, ...]
2. 初始化一个DataFrame
df = pd.DataFrame(columns=["歌单ID", "歌曲ID", "歌曲名", "热评内容"])
3. 遍历歌单ID列表
for playlist_id in playlist_ids:
# 获取歌单信息
playlist_soup = get_playlist_info(playlist_id)
# 解析歌曲信息
songs = get_song_info(playlist_soup)
# 获取CSRF Token
csrf_token = playlist_soup.find("meta", {"name": "csrf-token"})["content"]
# 遍历歌曲信息
for song in songs:
# 获取歌曲热评
comments = get_song_comments(song["song_id"], csrf_token)
# 提取热评内容
for comment in comments:
df = df.append({
"歌单ID": playlist_id,
"歌曲ID": song["song_id"],
"歌曲名": song["song_name"],
"热评内容": comment["content"]
}, ignore_index=True)
数据分析
1. 热评词频统计
from wordcloud import WordCloud
text = " ".join(df["热评内容"])
wordcloud = WordCloud(background_color="white").generate(text)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
2. 热评情感分析
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
df["情感得分"] = df["热评内容"].apply(lambda x: analyzer.polarity_scores(x)["compound"])
总结
通过Python的强大功能,我们成功构建了一个简单的爬虫,从网易云音乐歌单中爬取了歌曲热评数据,并对其进行了初步的数据分析。这一爬虫程序不仅可以帮助我们深入挖掘音乐世界的宝贵信息,还为我们提供了探索Python爬虫技术的绝佳平台。未来,我们将继续探索更复杂的数据爬取任务,为我们的知识库增添更多宝贵的财富。