网易云音乐评论爬取python完整代码
时间: 2023-11-28 19:02:56 浏览: 141
import requests
from bs4 import BeautifulSoup
# 定义要爬取的网易云音乐链接
url = 'https://music.163.com/song?id=1403423013'
# 发起请求获取页面内容
response = requests.get(url)
html = response.content
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(html, 'html.parser')
# 找到评论部分的标签
comments = soup.find_all('div', class_='m-cmmt')
# 循环遍历每个评论,并输出
for comment in comments:
user = comment.find('a', class_='s-fc7').text
content = comment.find('div', class_='cnt').text.strip()
print('用户:', user)
print('评论内容:', content)
print('------------------------')
# 这段完整代码可以爬取网易云音乐指定歌曲的评论内容,并输出用户和评论内容。可以根据需求进一步处理数据,比如存储到文件或者进行数据分析。同时也需要注意网易云音乐的反爬虫机制,爬取过程中需要加入一些反反爬虫的机制,比如设置请求头,使用代理等。
相关问题
基于python实现网易云音乐评论爬取
可以使用 Python 爬虫库 requests 和 BeautifulSoup 来实现网易云音乐评论爬取。
首先,使用 requests 库发送 GET 请求获取歌曲页面的 HTML 内容,然后使用 BeautifulSoup 库解析 HTML 内容,找到评论所在的标签和属性,获取评论内容。
以下是示例代码:
``` python
import requests
from bs4 import BeautifulSoup
# 歌曲 ID
song_id = '100000'
# 请求 URL
url = 'https://music.163.com/song?id=' + 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'}
# 发送 GET 请求
response = requests.get(url, headers=headers)
# 解析 HTML 内容
soup = BeautifulSoup(response.text, 'html.parser')
# 找到评论所在的标签和属性
comments = soup.find('div', {'class': 'cmmts j-flag'}).find_all('div', {'class': 'cnt f-brk'})
# 输出评论内容
for comment in comments:
print(comment.text.strip())
```
需要注意的是,为了避免被反爬虫机制检测到,可以设置请求头中的 User-Agent 字段模拟浏览器请求。同时,也需要注意代码的使用规范,不要过度请求对网站造成负面影响。
python爬取网易云评论_Python - 网易云热门评论爬取
下面是一个简单的Python爬取网易云音乐评论的示例代码,仅供参考:
``` python
import requests
import json
import time
import random
import pandas as pd
def get_comments(song_id, offset):
url = 'http://music.163.com/api/v1/resource/comments/R_SO_4_{}/?limit=100&offset={}'.format(song_id, offset)
headers = {
'Referer': 'http://music.163.com/song?id={}'.format(song_id),
'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'}
res = requests.get(url, headers=headers)
data = json.loads(res.text)
comments = data['comments']
return comments
def main(song_id):
comments_list = []
for i in range(1, 21):
comments = get_comments(song_id, i * 100)
for comment in comments:
comment_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(comment['time'] / 1000))
comments_list.append([comment['user']['nickname'], comment_time, comment['content']])
time.sleep(random.randint(2, 5))
df = pd.DataFrame(comments_list, columns=['user', 'time', 'content'])
df.to_csv('comments.csv', index=False)
if __name__ == '__main__':
main('歌曲ID')
```
需要将代码中的`歌曲ID`替换为实际需要爬取的歌曲ID,运行后会在当前目录下生成一个名为`comments.csv`的文件,包含了歌曲的评论用户、评论时间和评论内容。需要注意的是,为了防止被封IP,这里加入了随机的睡眠时间。