这里我们使用selenium模块,所以要下载自己Chrome对应版本的Chromedriver,关于Chromedriver的下载,这里上一篇别人的文章,也可以去百度如何下载配置。
这里我们爬取的是许嵩的雅俗共赏,想要爬取其它的评论则可以通过修改url,具体的url则可以去网易云网页端的网址获取,比如这是林俊杰的江南的网址:用网址去替换url。
随后我们上代码:
# -*- codeing = utf-8 -*-
# @Time : 2021/10/24 15:30
# @Author : 彭翔
# @File : 02.py
# @Software: PyCharm
from selenium import webdriver
import pandas as pd
driver = webdriver.Chrome()
url = 'https://music.163.com/#/song?id=411214279' # 歌曲页面的URL地址
driver.get(url)
driver.implicitly_wait(1) # 显式等待1秒
driver.switch_to.frame('contentFrame') # 切入contentFrame
comments_list = []
for i in range(100): # 爬取评论的页数
next_button = driver.find_element_by_xpath('//*[@class="m-cmmt"]/div[3]/div/a[11]') # 找到下一页的按钮
comments = driver.find_elements_by_xpath('//*[@class="m-cmmt"]/div[2]/div/div[2]/div[1]/div') # 找到评论
for item in comments:
index = item.text.index(':') + 1
comment = item.text[index:] # 解析评论
print(comment)
comments_list.append(comment)
driver.execute_script("arguments[0].click();", next_button) # 触发next_button的JS进入下一页评论
# 转换为dataframe,方便写入csv
df = pd.DataFrame(columns=['comment'], data=comments_list)
df.to_csv('comment.csv')
这里是获取到的评论。我用csv来储存的: