找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 96|回复: 0

python爬取网易云评论并做词云可视化

[复制链接]

2万

主题

162

回帖

18万

积分

管理员

积分
184732
发表于 2022-9-19 21:51:47 | 显示全部楼层 |阅读模式 IP:山东省青岛市 移动

登录后更精彩...O(∩_∩)O...

您需要 登录 才可以下载或查看,没有账号?立即注册

×
python爬取网易云评论并做词云可视化


[Python] 纯文本查看 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from  selenium.webdriver import ChromeOptions#反检测
from time import sleep
import time
import re
from selenium.webdriver.common.by import By
option=ChromeOptions()
option.add_experimental_option('excludeSwitches',['enable-automation'])
####
s = Service("../SELENIUM/chromedriver.exe")
driver = webdriver.Chrome(service=s,options=option)
##########################
driver.get('https://music.163.com/#/song?id=488249475')
#执行自动化
# selenium无法直接获取到嵌套页面里面的数据,主要是看iframe
driver.switch_to.frame(0)  # switch_to.frame()  切换到嵌套网页
driver.implicitly_wait(10)  # 让浏览器加载的时候, 等待渲染页面
#下拉页面, 直接下拉到页面的底部
js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight'
driver.execute_script(js)
#.解析数据
for i in range(1,101):#爬取的时候可以搞一个tqdm模块,要不然这100多页太慢了
    btn=driver.find_element(By.CLASS_NAME,'zbtn')
    btn.click()
    time.sleep(1.8)
    divs = driver.find_elements(By.CSS_SELECTOR,'.itm')  # 所有div  css语法: 定位到 html 数据/xpath/正则
    for div in divs:
        cnt = div.find_element(By.CSS_SELECTOR,'.cnt.f-brk').text
        id=cnt.split(":")[0]#以:作为分割
        cnt=cnt.split(":")[1]
        print(id,":",cnt)
        with open('哪里都是你.txt',mode="a",encoding='utf-8') as f:
            f.write(cnt)
            f.write('\n')
# print(resp.text)
sleep(100)
driver.quit()



词云图代码:


[Python] 纯文本查看 复制代码
#改生成图片的地址,改txt文件路径,该打开的图片名称
import matplotlib.pyplot as plt  # 绘制图像的模块
import jieba  # jieba分词
import re
import stylecloud
import collections
from PIL import Image
 
path_txt = 'D:\P\爬虫\音乐\哪里都是你.txt'
f = open(path_txt, 'r', encoding='utf-8').read()
# 文本预处理 :只提取出中文
new_data = re.findall('[\u4e00-\u9fa5]+', f, re.S)
new_data = "/".join(new_data)
# 文本分词
seg_list_exact = jieba.cut(new_data, cut_all=True)
result_list = []
with open('D:\P\爬虫\牛刀小试\豆瓣电影\停用词库.txt', encoding='utf-8') as f: #可根据需要打开停用词库,然后加上不想显示的词语
    con = f.readlines()
    stop_words = set()
    for i in con:
        i = i.replace("\n", "")   # 去掉读取每一行数据的\n
        stop_words.add(i)
for word in seg_list_exact:
    if word not in stop_words and len(word) > 1:
        result_list.append(word)
# print(result_list)
word_counts = collections.Counter(result_list)
# 词频统计:获取前100最高频的词
word_counts_top = word_counts.most_common(100)
print(word_counts_top)
# 绘制词云图
stylecloud.gen_stylecloud(text=' '.join(result_list[:1000]), # 提取500个词进行绘图
                          collocations=False, # 是否包括两个单词的搭配(二字组)
                          font_path=r'C:\Windows\Fonts\msyh.ttc', #设置字体,参考位置为  C:\Windows\Fonts\ ,根据里面的字体编号来设置
                          size=2000, # stylecloud 的大小
                          palette='cartocolors.qualitative.Bold_7', # 调色板,调色网址: [url=https://jiffyclub.github.io/palettable/]https://jiffyclub.github.io/palettable/[/url]
                          background_color='black', # 背景颜色
                          icon_name='fas fa-plane', # 形状的图标名称 蒙版网址:[url=https://fontawesome.com/icons?d=gallery&p=2&c=chat]https://fontawesome.com/icons?d=gallery&p=2&c=chat[/url],shopping,travel&m=free
                          gradient='horizontal', # 梯度方向
                          max_words=2000, # stylecloud 可包含的最大单词数
                          max_font_size=200, # stylecloud 中的最大字号
                          stopwords=True, # 布尔值,用于筛除常见禁用词
                          output_name='哪里都是你.png') # 输出图片
# 打开图片展示
img=Image.open('哪里都是你.png')
img.show()





Mac版本:爬取:

[Python] 纯文本查看 复制代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver import ChromeOptions#反检测
from time import sleep
import time
import re
from selenium.webdriver.common.by import By
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
####
s = Service("/usr/local/bin/chromedriver")
driver = webdriver.Chrome(service=s, options=option)
##########################
driver.get('https://music.163.com/#/song?id=488249475')
# 执行自动化
# selenium无法直接获取到嵌套页面里面的数据,主要是看iframe
driver.switch_to.frame(0)  # switch_to.frame()  切换到嵌套网页
driver.implicitly_wait(10)  # 让浏览器加载的时候, 等待渲染页面
# 下拉页面, 直接下拉到页面的底部
js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight'
driver.execute_script(js)
# 解析数据
for i in range(1, 101):  # 爬取的时候可以搞一个tqdm模块,要不然这100多页太慢了
    btn = driver.find_element(By.CLASS_NAME, 'zbtn.znxt')
    btn.click()
    time.sleep(1.8)
    divs = driver.find_elements(By.CSS_SELECTOR, '.itm')  # 所有div  css语法: 定位到 html 数据/xpath/正则
    for div in divs:
        cnt = div.find_element(By.CSS_SELECTOR, '.cnt.f-brk').text
        id = cnt.split(":")[0]    # 以:作为分割
        cnt = cnt.split(":")[1]
        print(id, ":", cnt)
        with open('哪里都是你.txt', mode="a", encoding='utf-8') as f:
            f.write(cnt)
            f.write('\n')
# print(resp.text)
sleep(100)
driver.quit()

生成图片:
[Python] 纯文本查看 复制代码
# 改生成图片的地址,改txt文件路径,该打开的图片名称
import matplotlib.pyplot as plt  # 绘制图像的模块
import jieba  # jieba分词
import re
import stylecloud
import collections
from PIL import Image

path_txt = '哪里都是你.txt'
f = open(path_txt, 'r', encoding='utf-8').read()
# 文本预处理 :只提取出中文
new_data = re.findall('[\u4e00-\u9fa5]+', f, re.S)
new_data = "/".join(new_data)
# 文本分词
seg_list_exact = jieba.cut(new_data, cut_all=True)
result_list = []
with open('停用词库.txt', encoding='utf-8') as f:  # 可根据需要打开停用词库,然后加上不想显示的词语
    con = f.readlines()
    stop_words = set()
    for i in con:
        i = i.replace("\n", "")  # 去掉读取每一行数据的\n
        stop_words.add(i)
for word in seg_list_exact:
    if word not in stop_words and len(word) > 1:
        result_list.append(word)
# print(result_list)
word_counts = collections.Counter(result_list)
# 词频统计:获取前100最高频的词
word_counts_top = word_counts.most_common(100)
print(word_counts_top)
# 绘制词云图
stylecloud.gen_stylecloud(text=' '.join(result_list[:1000]),  # 提取500个词进行绘图
                          collocations=False,  # 是否包括两个单词的搭配(二字组)
                          font_path=r'/System/Library/Fonts/STHeiti Medium.ttc',  # 设置字体,参考位置为  C:\Windows\Fonts\ ,根据里面的字体编号来设置
                          size=2000,  # stylecloud 的大小
                          palette='cartocolors.qualitative.Bold_7',  # 调色板,调色网址: [url]https://jiffyclub.github.io/palettable/[/url]
                          background_color='black',  # 背景颜色
                          icon_name='fas fa-plane',
                          # 形状的图标名称 蒙版网址:[url]https://fontawesome.com/icons?d=gallery&p=2&c=chat[/url],shopping,travel&m=free
                          gradient='horizontal',  # 梯度方向
                          max_words=2000,  # stylecloud 可包含的最大单词数
                          max_font_size=200,  # stylecloud 中的最大字号
                          stopwords=True,  # 布尔值,用于筛除常见禁用词
                          output_name='哪里都是你.png')  # 输出图片
# 打开图片展示
img = Image.open('哪里都是你.png')
img.show()

图片如下:


1.png


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|哩布大模型|Civitai大模型|IP定位|图反推|站长素材|deepseek|即梦视频|阿狗工具|花瓣网|pinterest|php手册|宝塔文档|CyberChef|猫捉鱼铃|手机版|小黑屋|下载狗|IPS|在线工具|分享屋 ( 鲁ICP备2021028754号 )

GMT+8, 2025-5-5 09:31

Powered by 分享屋 X3.5 Licensed

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表