爬取酷狗华语新歌榜数据使用bs库保存为csv
时间: 2023-03-16 20:50:17 浏览: 180
好的,以下是使用bs库爬取酷狗华语新歌榜数据并保存为csv文件的步骤:
1. 导入需要的库
```python
import requests
from bs4 import BeautifulSoup
import csv
```
2. 发送请求获取网页内容
```python
url = 'http://www.kugou.com/yy/rank/home/1-8888.html?from=rank'
headers = {
'User-Agent': 'Mozilla/5. (Windows NT 10.; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58..3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
```
3. 解析网页内容
```python
soup = BeautifulSoup(response.text, 'html.parser')
song_list = soup.find_all('div', class_='pc_temp_songlist')
```
4. 提取需要的数据并保存为csv文件
```python
with open('kugou.csv', 'w', newline='', encoding='utf-8-sig') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['排名', '歌曲名称', '歌手', '专辑'])
for song in song_list:
song_name = song.find('a', class_='pc_temp_songname').text.strip()
singer = song.find('a', class_='pc_temp_singer').text.strip()
album = song.find('a', class_='pc_temp_album').text.strip()
rank = song.find('span', class_='pc_temp_num').text.strip()
writer.writerow([rank, song_name, singer, album])
```
以上就是使用bs库爬取酷狗华语新歌榜数据并保存为csv文件的全部步骤。
阅读全文