酷狗音乐榜爬虫python按要求
时间: 2025-06-29 07:04:34 浏览: 7
### 使用 Python 编写爬虫抓取酷狗音乐排行榜数据
为了实现这一目标,可以采用 `requests` 库获取网页内容,并利用 `BeautifulSoup` 解析 HTML 文档中的结构化信息。对于动态加载的内容,则可能需要用到 `Selenium` 来模拟浏览器行为。
#### 安装必要的库
首先安装所需的第三方库:
```bash
pip install requests beautifulsoup4 selenium
```
#### 获取页面源码
通过发送 HTTP 请求访问酷狗音乐的排行榜页面,获取其返回的 HTML 响应体作为后续处理的基础[^1]。
```python
import requests
from bs4 import BeautifulSoup
url = "https://www.kugou.com/yy/rank/home/1-8888.html?from=rank"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
}
response = requests.get(url, headers=headers)
html_content = response.text
```
#### 数据解析与提取
使用 `BeautifulSoup` 对获得的 HTML 进行分析,定位到包含歌曲名、歌手以及链接等元素的位置,并将其转换成易于操作的形式存储起来[^2]。
```python
soup = BeautifulSoup(html_content, 'lxml')
song_list = []
for item in soup.select('.pc_temp_songlist .pc_temp_songname'):
name = item.get_text(strip=True).split('-')[1].strip()
artist = item.get('title').split('-')[0].strip()
link = "http:" + item.a['href']
song_info = {"name": name,
"artist": artist,
"link": link}
song_list.append(song_info)
print(f"共找到 {len(song_list)} 首歌")
```
#### 存储结果至 CSV 文件
最后一步就是把收集好的资料导出为表格形式以便查看或进一步加工[^3]。
```python
import pandas as pd
df = pd.DataFrame(song_list)
csv_file_path = './kugou_top_songs.csv'
df.to_csv(csv_file_path, index=False, encoding='utf_8_sig')
print(f"已成功保存至 '{csv_file_path}'")
```
阅读全文
相关推荐

















