爬取网易云音乐评论!python 爬虫入门实战(六)selenium 入门!

说到爬虫,第一时间可能就会想到网易云音乐的评论。网易云音乐评论里藏了许多宝藏,那么让咱们一块儿学习如何用 python 挖宝藏吧!python

file

既然是宝藏,确定是用要用钥匙加密的。打开 Chrome 分析 Headers 以下。git

file

这参数看起来挺复杂的,咱们就不用 requests 去调用这个连接了。github

此次使用的是 selenium ! 一个浏览器自动化测试框架!经过它能够模拟手动操做浏览器!web

为此咱们要准备好驱动器 chromedriver 和 chrome 浏览器。chrome

file

chromedriver 能够在淘宝镜像中下载,选择与 chrome 浏览器对应的版本进行下载。下载地址以下。
http://npm.taobao.org/mirrors...npm

整个项目使用了 python3 与一些第三方库。参考以下。json

from selenium import webdriver
import jieba
from wordcloud import WordCloud
from PIL import Image
import numpy as np

而后配置 config.json segmentfault

file

{
  "id":"1336789644",
  "page": 200,
  "useCache": true,
  "font_path": "SimHei.ttf",
  "mask": "mask.png",
  "chromedriver": "chromedriver"
}

运行 sound.py 就会生成词云图。浏览器

file

以及全部的评论数据并发

file

看了使用方法,接下来进入分析环节!

file

找到网易云音乐的地址并发现规律,并使用 webdriver 打开!

file

driver = webdriver.Chrome(CONFIG['chromedriver'])
driver.get(f'https://music.163.com/#/song?id={SOUND_ID}')

接着让 driver 跳入到评论框的 frame 里。

driver.switch_to.frame('g_iframe')

为什么这么作?由于在 frame 结构里没法用 xpath 解析到。而评论数据正好在这个 iframe 中。

file

选中其中一个评论,分析其格式结构,能够看到都是在同一个 class 名内。

file

编写对应的 xpath ,获得全部的评论列表。

element_list = driver.find_elements_by_xpath('//div[@class="cnt f-brk"]')

选择下一页按钮,分析其格式结构,能够看到 class 名是以一个前缀为开头的。

file

编写对应的 xpath ,获得下一页按钮,并在须要的时候模拟点击。

next_button = driver.find_element_by_xpath('//a[starts-with(@class,"zbtn znxt js-n-")]')
driver.execute_script('arguments[0].click();', next_button)

数据分析结束后,该生成结果喽。

file

将评论列表保存为 json。

with open(filePath,'w') as f:
    json.dump(comments_list,f, ensure_ascii=False, indent=4)

使用 jieba 分词和 wordcloud 生成词云图。

# 词云处理
image_mask = np.array(Image.open(CONFIG['mask']))
wordlist = jieba.cut(';'.join(comments_list))
wordcloud = WordCloud(font_path=CONFIG['font_path'], background_color='white', mask=image_mask, scale=1.5).generate(' '.join(wordlist))
# 保存图
wordcloud.to_file(f'./result/{SOUND_ID}-{PAGES}.png')

以上就是使用 selenium 爬取网易云音乐评论的整个步骤喽!


本文仅供我的学习交流使用,请勿用于其余用途!


完整代码
参考资料

相关文章
相关标签/搜索