Python爬虫爬取网易云音乐歌曲评论的代码
时间: 2024-12-25 11:24:32 浏览: 3
Python爬虫使用`requests`库获取网页内容,然后通过解析HTML(如BeautifulSoup或lxml)提取数据,特别是在网易云音乐这类网站上。以下是一个基本的示例,展示如何爬取歌曲评论:
```python
import requests
from bs4 import BeautifulSoup
# 网易云音乐API地址
base_url = "https://music.163.com/#/song?id=YOUR_SONG_ID"
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'}
def get_song_comments(song_id):
response = requests.get(base_url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 查找评论区域
comments_area = soup.find('div', {'class': 'comment-list'})
# 如果找到评论区,遍历每个评论
if comments_area:
comments = comments_area.find_all('li')
for comment in comments:
username = comment.find('span', {'class': 'author'}).text.strip()
content = comment.find('p', {'class': 'content'}).text.strip()
print(f"用户名: {username}\n评论内容: {content}\n")
else:
print("未找到评论区或网络请求失败.")
# 替换 `YOUR_SONG_ID` 为你要爬取的具体歌曲ID
get_song_comments(YOUR_SONG_ID)
```
阅读全文