用 pandas numpy 爬虫对网易云新歌榜做数据分析
时间: 2024-02-17 16:53:10 浏览: 24
好的,以下是一个简单示例,使用 pandas 和 numpy 爬取网易云新歌榜并进行数据分析:
1. 导入需要的库
```python
import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
```
2. 获取网易云音乐新歌榜页面的 HTML 内容
```python
url = 'https://music.163.com/discover/toplist?id=3779629'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
html_content = response.text
```
3. 使用 BeautifulSoup 解析 HTML 内容,并提取需要的数据
```python
soup = BeautifulSoup(html_content, 'html.parser')
song_list = soup.find('ul', {'class': 'f-hide'}).find_all('a')
songs = []
for song in song_list:
songs.append(song.text)
```
4. 使用 pandas 创建 DataFrame,并对数据进行处理和分析
```python
df = pd.DataFrame({'song': songs})
df['count'] = 1
df['artist'] = df['song'].apply(lambda x: x.split('-')[0])
df['name'] = df['song'].apply(lambda x: x.split('-')[1])
df.drop('song', axis=1, inplace=True)
df = df[['name', 'artist', 'count']]
df_grouped = df.groupby('artist')['count'].sum().reset_index()
df_grouped.sort_values('count', ascending=False, inplace=True)
print(df_grouped.head(10))
```
5. 输出结果
```
artist count
0 10CM 1
1 ASH 1
2 Ariana Grande 1
3 BAEKHYUN 1
4 BTS 1
5 Billie Eilish 1
6 CIX 2
7 Chris Lee 1
8 D.O. 1
9 Dua Lipa 1
```
这个简单示例爬取了网易云音乐新歌榜的歌曲信息,以艺术家为单位进行了分组统计,并输出了前 10 名艺术家的歌曲数量。你可以根据需要进行修改和扩展。