爬取豆瓣影评并生成词云

使用python wordcloud库进行词云可视化。利用所学爬虫知识爬取豆瓣电影中电影的评论作为生成词云的文本数据,然后利用词云生成文本数据的可视化图片。

截取cookies🏎

使用各类浏览器的开发者工具,监测网络请求,截取cookies。 

以Firefox为例:

  1. 按F12打开开发者工具,切换到网络Tab。
  2. 此时登陆豆瓣,开发者工具窗口会截取大量的请求。
  3. 寻找其中文件类型为html的项,点击进入详情,在下图的位置找到Cookie,复制到一个文本文件中备用,以下为cookies截取部分:
    在这里插入图片描述
    然后将上图选中部分复制到文本文件中(需自己创建文件名为cookies.txt的文件)。

编写爬虫🚑

#coding = utf-8
import requests
import time
import random
from bs4 import BeautifulSoup

abss = 'https://movie.douban.com/subject/20495023/comments'
firstPag_url = 'https://movie.douban.com/subject/20495023/comments?start=20&limit=20&sort=new_score&status=P&percent_type='
url = 'https://movie.douban.com/subject/20495023/comments?start=0&limit=20&sort=new_score&status=P'
header = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0',
'Connection':'keep-alive'
}

def get_data(html):
    # 获取所需要的页面数据
    soup = BeautifulSoup(html, 'lxml')
    comment_list = soup.select('.comment > p')
    next_page = soup.select('#paginator > a')[2].get('href')
    date_nodes = soup.select('..comment-time')
    return comment_list, next_page, date_nodes

def get_cookies(path):
    # 获取cookies
    f_cookies = open(path, 'r')
    cookies ={}
    for line in f_cookies.read().split(';'): # 将Cookies字符串其转换为字典
        name ,value = line.strip().split('=', 1)
        cookies[name] = value
    return cookies

if __name__ == '__main__':
    cookies = get_cookies('./cookies.txt') # cookies文件保存的前面所述的cookies
    html = requests.get(firstPag_url, cookies=cookies,headers=header).content
    comment_list, next_page, date_nodes = get_data(html) #首先从第一个页面处理
    soup = BeautifulSoup(html, 'lxml')
    while (next_page): #不断的处理接下来的页面
        print(abss + next_page)
        html = requests.get(abss + next_page, cookies=cookies, headers=header).content
        comment_list, next_page, date_nodes = get_data(html)
        soup = BeautifulSoup(html, 'lxml')
        comment_list, next_page,date_nodes = get_data(html)
        with open("comments.txt", 'a', encoding='utf-8')as f:
            for ind in range(len(comment_list)):
                comment = comment_list[ind];
                date = date_nodes[ind]
                comment = comment.get_text().strip().replace("\n", "")
                date= date.get_text().strip()
                f.writelines(date+u'\n' +comment + u'\n')
        time.sleep(1 + float(random.randint(1, 100)) / 20)
)
运行截图:

在这里插入图片描述

爬取结束后,会在同级目录生成comment.txt文件,如下:

在这里插入图片描述

处理文本数据🚔

在爬取到文本数据以后,我们需要对其进行一些预处理以利用它生成词云图 
代码如下:
# -*- coding:utf-8 -*-
#  @Time : 2017-11-28 10:52
#  @File : wordcloud_generate.py
#  @Description:

from wordcloud import WordCloud
import jieba
import matplotlib.pyplot as plt

f_comment = open("./comments.txt",'rb')
words = []
for line in f_comment.readlines():
    if(len(line))==12:
        continue
    A = jieba.cut(line)
    words.append(" ".join(A))
# 去除停用词
stopwords = [',','。','【','】', '”','“',',','《','》','!','、','?','.','…','1','2','3','4','5','[',']','(',')',' ']
new_words = []
for sent in words :
    word_in = sent.split(' ')
    new_word_in = []
    for word in word_in:
        if word in stopwords:
            continue
        else:
            new_word_in.append(word)
    new_sent = " ".join(new_word_in)
    new_words.append(new_sent)

final_words = []
for sent in new_words:
    sent = sent.split(' ')
    final_words +=sent
final_words_flt = []
for word in final_words:
    if word == ' ':
        continue
    else:
        final_words_flt.append(word)
text = " ".join(final_words_flt)
运行截图:

在这里插入图片描述

生成词云图🚜

使用python的wordcloud模块来生成词云图。代码如下:
from wordcloud import WordCloud,ImageColorGenerator
from scipy.misc import imread
import matplotlib.pyplot as plt
font = r'E:\FZSTJW.TTF'
bk = imread("./background.jpg") # 设置背景文件
wc = WordCloud(collocations=False, mask = bk, font_path=font, width=1400, height=1400, margin=2).generate( text .lower())
image_colors = ImageColorGenerator(bk) # 读取背景文件色彩
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis("off")
plt.figure()
plt.imshow(bk, cmap=plt.cm.gray)
plt.axis("off")
plt.show()
wc.to_file('word_cloud1.png')
最终结果如下:

在这里插入图片描述

  • 7
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白羊是小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值