改进一下代码,但这次不需要数据可视化
时间: 2024-03-29 13:35:57 浏览: 11
好的,这是改进后的代码:
```python
import requests
from bs4 import BeautifulSoup
import re
import pandas as pd
url = 'https://music.163.com/discover/toplist?id=19723756'
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)
soup = BeautifulSoup(response.text, 'html.parser')
song_list = soup.find('ul', {'class': 'f-hide'})
song_items = song_list.find_all('li')
data = []
for song_item in song_items:
song_title = song_item.find('a').text.strip()
song_id = song_item.find('a')['href'].split('=')[1]
song_url = f'https://music.163.com/song/media/outer/url?id={song_id}.mp3'
song_artists = song_item.find('span', {'class': 's-fc3'}).text.strip()
song_artists = re.sub('\s+', ' ', song_artists)
song_artists = re.sub('/', ', ', song_artists)
data.append([song_title, song_url, song_artists])
df = pd.DataFrame(data, columns=['Title', 'URL', 'Artists'])
df.to_excel('song_list.xlsx', index=False)
```
改进后的代码将歌曲的时长改为了歌曲的 URL,方便后续下载。同时,也将歌单页面的 URL 改为了不带 "#" 的版本。
需要注意的是,如果歌曲的 URL 是需要登录后才能访问的,那么这个代码就不适用了,需要使用其他方法来下载歌曲。