代码地址如下:
http://www.demodashi.com/demo/13257.html

1. 需求说明

本项目基于Python爬虫,爬取豆瓣电影上关于复仇者联盟3的所有影评,并保存至本地文件。然后对影评进行分词分析,使用词云生成树人格鲁特的形象照片。

2. 代码实现

此部分主要解释Python爬虫部分及使用词云生成图像的代码

Python爬虫

首先获取需要爬取的网页地址,然后通过requests.get()方式去获取网页,代码如下:

# 获取网页
def getHtml(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
return r.text
except:
return ''

获取到网页之后,对网页中的元素进行正则匹配,找到评论相关的元素,并获取。

# 获取某个网页中的影评
def getComment(html):
soup = BeautifulSoup(html, 'html.parser')
comments_list = []
comment_nodes = soup.select('.comment > p')
for node in comment_nodes:
comments_list.append(node.get_text().strip().replace("\n", "") + u'\n')
return comments_list

将爬取到的影评保存至文本文件中,以备后续分析使用。

def saveCommentText(fpath):
pre_url = "https://movie.douban.com/subject/24773958/comments?"
depth = 8
with open(fpath, 'a', encoding='utf-8') as f:
for i in range(depth):
url = pre_url + 'start=' + str(20 * i) + '&limit=20&sort=new_score&' + 'status=P'
html = getHtml(url)
f.writelines(getComment(html))
time.sleep(1 + float(random.randint(1, 20)) / 20)
基于词云生成图像

注释比较详细,可以看注释说明

def drawWordcloud():
with codecs.open('text.txt', encoding='utf-8') as f:
comment_text = f.read()
# 设置背景图片,可替换为img目录下的任何一张图片
color_mask = imread("img\Groot4.jpeg")
# 停用词设置
Stopwords = [u'就是', u'电影', u'你们', u'这么', u'不过', u'但是',
u'除了', u'时候', u'已经', u'可以', u'只是', u'还是', u'只有', u'不要', u'觉得', u','u'。']
# 设置词云属性
cloud = WordCloud(font_path="simhei.ttf",
background_color='white',
max_words=260,
max_font_size=150,
min_font_size=4,
mask=color_mask,
stopwords=Stopwords)
# 生成词云, 可以用generate输入全部文本,也可以我们计算好词频后使用generate_from_frequencies函数
word_cloud = cloud.generate(comment_text)
# 从背景图片生成颜色值(注意图片的大小)
image_colors = ImageColorGenerator(color_mask) # 显示图片
plt.imshow(cloud)
plt.axis("off")
# 绘制词云
plt.figure()
plt.imshow(cloud.recolor(color_func=image_colors))
plt.axis("off")
plt.figure()
plt.imshow(color_mask, cmap=plt.cm.gray)
plt.axis("off")
plt.show()
# 保存图片
word_cloud.to_file("img\comment_cloud.jpg")
为了方便阅读,这里贴出整体过程编码:
def getHtml(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
return r.text
except:
return '' def getComment(html):
soup = BeautifulSoup(html, 'html.parser')
comments_list = []
comment_nodes = soup.select('.comment > p')
for node in comment_nodes:
comments_list.append(node.get_text().strip().replace("\n", "") + u'\n')
return comments_list def saveCommentText(fpath):
pre_url = "https://movie.douban.com/subject/24773958/comments?"
depth = 8
with open(fpath, 'a', encoding='utf-8') as f:
for i in range(depth):
url = pre_url + 'start=' + str(20 * i) + '&limit=20&sort=new_score&' + 'status=P'
html = getHtml(url)
f.writelines(getComment(html))
time.sleep(1 + float(random.randint(1, 20)) / 20) def cutWords(fpath):
text = ''
with open(fpath, 'r', encoding='utf-8') as fin:
for line in fin.readlines():
line = line.strip('\n')
text += ' '.join(jieba.cut(line))
text += ' '
with codecs.open('text.txt', 'a', encoding='utf-8') as f:
f.write(text) def drawWordcloud():
with codecs.open('text.txt', encoding='utf-8') as f:
comment_text = f.read()
# 设置背景图片
color_mask = imread("img\Groot4.jpeg")
# 停用词设置
Stopwords = [u'就是', u'电影', u'你们', u'这么', u'不过', u'但是',
u'除了', u'时候', u'已经', u'可以', u'只是', u'还是', u'只有', u'不要', u'觉得', u','u'。']
# 设置词云属性
cloud = WordCloud(font_path="simhei.ttf",
background_color='white',
max_words=260,
max_font_size=150,
min_font_size=4,
mask=color_mask,
stopwords=Stopwords)
# 生成词云, 可以用generate输入全部文本,也可以我们计算好词频后使用generate_from_frequencies函数
word_cloud = cloud.generate(comment_text)
# 从背景图片生成颜色值(注意图片的大小)
image_colors = ImageColorGenerator(color_mask) # 显示图片
plt.imshow(cloud)
plt.axis("off")
# 绘制词云
plt.figure()
plt.imshow(cloud.recolor(color_func=image_colors))
plt.axis("off")
plt.figure()
plt.imshow(color_mask, cmap=plt.cm.gray)
plt.axis("off")
plt.show()
# 保存图片
word_cloud.to_file("img\comment_cloud.jpg")

三、项目结构

项目结构

注意整个项目只有一个源码文件,其他的为图片文件

四、运行效果图

一大波格鲁特来袭

格鲁特1号

格鲁特2号

格鲁特3号

格鲁特4号

Python爬取豆瓣《复仇者联盟3》评论并生成乖萌的格鲁特

代码地址如下:
http://www.demodashi.com/demo/13257.html

注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权

Python爬取豆瓣《复仇者联盟3》评论并生成乖萌的格鲁特的更多相关文章

  1. python 爬取豆瓣电影短评并wordcloud生成词云图

    最近学到数据可视化到了词云图,正好学到爬虫,各种爬网站 [实验名称] 爬取豆瓣电影<千与千寻>的评论并生成词云 1. 利用爬虫获得电影评论的文本数据 2. 处理文本数据生成词云图 第一步, ...

  2. Python爬取豆瓣指定书籍的短评

    Python爬取豆瓣指定书籍的短评 #!/usr/bin/python # coding=utf-8 import re import sys import time import random im ...

  3. 利用Python爬取豆瓣电影

    目标:使用Python爬取豆瓣电影并保存MongoDB数据库中 我们先来看一下通过浏览器的方式来筛选某些特定的电影: 我们把URL来复制出来分析分析: https://movie.douban.com ...

  4. Python爬取豆瓣电影top

    Python爬取豆瓣电影top250 下面以四种方法去解析数据,前面三种以插件库来解析,第四种以正则表达式去解析. xpath pyquery beaufifulsoup re 爬取信息:名称  评分 ...

  5. python 爬取豆瓣电影评论,并进行词云展示及出现的问题解决办法

    本文旨在提供爬取豆瓣电影<我不是药神>评论和词云展示的代码样例 1.分析URL 2.爬取前10页评论 3.进行词云展示 1.分析URL 我不是药神 短评 第一页url https://mo ...

  6. python 爬取豆瓣书籍信息

    继爬取 猫眼电影TOP100榜单 之后,再来爬一下豆瓣的书籍信息(主要是书的信息,评分及占比,评论并未爬取).原创,转载请联系我. 需求:爬取豆瓣某类型标签下的所有书籍的详细信息及评分 语言:pyth ...

  7. Python爬取豆瓣音乐存储MongoDB数据库(Python爬虫实战1)

    1.  爬虫设计的技术 1)数据获取,通过http获取网站的数据,如urllib,urllib2,requests等模块: 2)数据提取,将web站点所获取的数据进行处理,获取所需要的数据,常使用的技 ...

  8. 零基础爬虫----python爬取豆瓣电影top250的信息(转)

    今天利用xpath写了一个小爬虫,比较适合一些爬虫新手来学习.话不多说,开始今天的正题,我会利用一个案例来介绍下xpath如何对网页进行解析的,以及如何对信息进行提取的. python环境:pytho ...

  9. python爬取豆瓣小组700+话题加回复啦啦啦python open file with a variable name

    需求:爬取豆瓣小组所有话题(话题title,内容,作者,发布时间),及回复(最佳回复,普通回复,回复_回复,翻页回复,0回复) 解决:1. 先爬取小组下,所有的主题链接,通过定位nextpage翻页获 ...

随机推荐

  1. scrapy 工作流程

    Scrapy的整个数据处理流程由Scrapy引擎进行控制,其主要的运行方式为: 引擎打开一个域名,蜘蛛处理这个域名,然后获取第一个待爬取的URL. 引擎从蜘蛛那获取第一个需要爬取的URL,然后作为请求 ...

  2. CF GukiZ hates Boxes 【二分+贪心】

    Professor GukiZ is concerned about making his way to school, because massive piles of boxes are bloc ...

  3. codeforces Round #440 C Maximum splitting【数学/素数与合数/思维/贪心】

    C. Maximum splitting time limit per test 2 seconds memory limit per test 256 megabytes input standar ...

  4. 7、Flask实战第7天:Jinjia2模板

    Jinja2模板介绍和查找路径 在前面的章节中,视图只是直接返回文本,然而在实际生产环境中其实很少这样用,因为实际的页面大多带有样式和复杂逻辑的HTML代码,这可以让浏览器其渲染出非常漂亮的页面. 我 ...

  5. ASP.NET Core 2.2 基础知识(五) 环境

    一.环境变量 系统启动时,会读取环境变量 ASPNETCORE_ENVIRONMENT ,并将该变量的值存储在 IHostingEnvironment.EnvironmentName 字段中.如: 新 ...

  6. 【分块】【树状数组】bzoj3744 Gty的妹子序列

    离散化,分块. 预处理出:ans[i][j] 第i块到第j块的逆序对数. f[i][j] 第1~i块中大于j的数的个数. g[i][j] 第1~j块中小于j的数的个数. 每次询问时对于整块部分可以O( ...

  7. noip2017集训测试赛(三) Problem B: mex [补档]

    Description 给你一个无限长的数组,初始的时候都为0,有3种操作: 操作1是把给定区间[l,r][l,r] 设为1, 操作2是把给定区间[l,r][l,r] 设为0, 操作3把给定区间[l, ...

  8. angularjs自动加载和手动加载

    (一)自动加载 ng-app是angular的一个指令,代表一个angular应用(也叫模块).使用ng-app或ng-app=""来标记一个DOM结点,让框架会自动加载.也就是说 ...

  9. apk打包

    1.在导航栏中选择Builder->Generate Signed Apk 2.新建点击Creat new... 3.注意路径后面写apk的名字(这个名字将会显示在手机软件的下方)

  10. HTTP Basic 验证客户端 C#实现笔记

    HTTP Basic 验证客户端的原理:把HTTP头重的ContentType设置为:application/x-www-form-urlencoded如果HTTP头没有Authorization,那 ...