最近看到电影,也看了很多的评论,想了解下大多人对相关电影的评论,正好也在学习Python,就利用其爬虫的强大能力,这里利用Python3.6.1

下面是相关代码:

 #coding:utf-8
__author__ = 'hang' import warnings
warnings.filterwarnings("ignore")
import jieba #分词包
import numpy #numpy计算包
import codecs #codecs提供的open方法来指定打开的文件的语言编码,它会在读取的时候自动转换为内部unicode
import re
import pandas as pd
import matplotlib.pyplot as plt
from urllib import request
from bs4 import BeautifulSoup as bs
# %matplotlib inline (ipython中应用)
# from skimage import data
import matplotlib
matplotlib.rcParams['figure.figsize'] = (10.0, 5.0)
from wordcloud import WordCloud#词云包 class KetWord:
def __init__(self,name,count):
self.name =name
self.count = count def __cmp__(self, other): if isinstance(KetWord,other):
if self.count > other.count:
return 1
elif self.count < other.count:
return -1
else:
return 0 def __str__(self):
return '[name='+ self.name +':count='+ str(self.count) +']'
#分析网页函数
def getNowPlayingMovie_list():
resp = request.urlopen('https://movie.douban.com/nowplaying/hangzhou/')
html_data = resp.read().decode('utf-8')
soup = bs(html_data, 'html.parser')
nowplaying_movie = soup.find_all('div', id='nowplaying')
nowplaying_movie_list = nowplaying_movie[0].find_all('li', class_='list-item')
nowplaying_list = []
for item in nowplaying_movie_list:
nowplaying_dict = {}
nowplaying_dict['id'] = item['data-subject']
for tag_img_item in item.find_all('img'):
nowplaying_dict['name'] = tag_img_item['alt']
nowplaying_list.append(nowplaying_dict)
return nowplaying_list #爬取评论函数
def getCommentsById(movieId, pageNum):
eachCommentList = [];
if pageNum>0:
start = (pageNum-1) * 20
else:
return False
requrl = 'https://movie.douban.com/subject/' + movieId + '/comments' +'?' +'start=' + str(start) + '&limit=20'
print(requrl)
resp = request.urlopen(requrl)
html_data = resp.read().decode('utf-8')
soup = bs(html_data, 'html.parser')
comment_div_lits = soup.find_all('div', class_='comment')
for item in comment_div_lits:
if item.find_all('p')[0].string is not None:
eachCommentList.append(item.find_all('p')[0].string)
return eachCommentList def main():
#循环获取第一个电影的前10页评论
commentList = []
NowPlayingMovie_list = getNowPlayingMovie_list()
print('common=',NowPlayingMovie_list)
#获取id电影[{'id': '11502973', 'name': '星际特工:千星之城'}, {'id': '25933890', 'name': '极盗车神'}, {'id': '25849480', 'name': '赛车总动员3:极速挑战'},
# {'id': '26607693', 'name': '敦刻尔克'}, {'id': '26363254', 'name': '战狼2'}, {'id': '26826398', 'name': '杀破狼·贪狼'}, {'id': '26816086', 'name': '银魂 真人版'},
# {'id': '26430107', 'name': '二十二'}, {'id': '26759539', 'name': '十万个冷笑话2'}, {'id': '26752106', 'name': '黑白迷宫'}, {'id': '26647876', 'name': '地球:神奇的一天'},
# {'id': '26969037', 'name': '赛尔号大电影6:圣者无敌'}, {'id': '25980443', 'name': '海边的曼彻斯特'}, {'id': '26760160', 'name': '破·局'},
# {'id': '27040349', 'name': '二次初恋'}, {'id': '22232939', 'name': '大耳朵图图之美食狂想曲'}, {'id': '25857966', 'name': '鲛珠传'}, {'id': '26698000', 'name': '心理罪'},
# {'id': '26692823', 'name': '建军大业'}, {'id': '25823277', 'name': '三生三世十里桃花'}, {'id': '2999500', 'name': '七天'}, {'id': '27107261', 'name': '一路向爱'},
# {'id': '25858758', 'name': '侠盗联盟'}, {'id': '26790961', 'name': '闪光少女'}, {'id': '26991769', 'name': '恐怖毕业照2'}, {'id': '25812712', 'name': '神偷奶爸3'},
# {'id': '27107265', 'name': '杜丽娘'}]
for i in range(10):
num = i + 1
commentList_temp = getCommentsById(NowPlayingMovie_list[4]['id'], num)
commentList.append(commentList_temp) #将列表中的数据转换为字符串
comments = ''
for k in range(len(commentList)):
comments = comments + (str(commentList[k])).strip() #使用正则表达式去除标点符号
pattern = re.compile(r'[\u4e00-\u9fa5]+')
filterdata = re.findall(pattern, comments)
cleaned_comments = ''.join(filterdata) #使用结巴分词进行中文分词
segment = jieba.lcut(cleaned_comments)
words_df=pd.DataFrame({'segment':segment}) #去掉停用词
stopwords=pd.read_csv("stopwords.txt",index_col=False,quoting=3,sep="\t",names=['stopword'], encoding='utf-8')#quoting=3全不引用
words_df=words_df[~words_df.segment.isin(stopwords.stopword)] #统计词频
words_stat=words_df.groupby(by=['segment'])['segment'].agg({"计数":numpy.size})
words_stat=words_stat.reset_index().sort_values(by=["计数"],ascending=False) #用词云进行显示
wordcloud=WordCloud(font_path="simhei.ttf",background_color="white",max_font_size=80)
word_frequence = {x[0]:x[1] for x in words_stat.head(1000).values} #利用字典存放
word_frequence_list = {}
x_val = []
y_val = []
for key in word_frequence:
word_frequence_list[str(key)] = word_frequence[key] wordcloud=wordcloud.generate_from_frequencies(word_frequence_list)
print(word_frequence_list) # print('x=',x_val)
# print('y=',y_val)
# map = dict()
# for i in range(len(y_val)):
# # key_word = KetWord(x_val[i],y_val[i])
# map[i] = KetWord(x_val[i],y_val[i])
# for key in map:
# print('word=',map[key])
# plt.plot(x_val,y_val)
# plt.show()
plt.imshow(wordcloud)
#既然是IPython的内置magic函数,那么在Pycharm中是不会支持的。但是我们可以在matplotlib中的pyplot身上下功夫,pyplot不会不提供展示图像的功能。
plt.colorbar()
plt.show() #主函数
main()

爬虫python的更多相关文章

  1. 网易云音乐综合爬虫python库NetCloud v1版本发布

    以前写的太烂了,这次基本把之前的代码全部重构了一遍.github地址是:NetCloud.下面是简单的介绍以及quick start. NetCloud--一个完善的网易云音乐综合爬虫Python库 ...

  2. 定向爬虫 - Python模拟新浪微博登录

    当我们试图从新浪微博抓取数据时,我们会发现网页上提示未登录,无法查看其他用户的信息. 模拟登录是定向爬虫制作中一个必须克服的问题,只有这样才能爬取到更多的内容. 实现微博登录的方法有很多,一般我们在模 ...

  3. 百度图片爬虫-python版-如何爬取百度图片?

    上一篇我写了如何爬取百度网盘的爬虫,在这里还是重温一下,把链接附上: http://www.cnblogs.com/huangxie/p/5473273.html 这一篇我想写写如何爬取百度图片的爬虫 ...

  4. 纯手工打造简单分布式爬虫(Python)

    前言 这次分享的文章是我<Python爬虫开发与项目实战>基础篇 第七章的内容,关于如何手工打造简单分布式爬虫 (如果大家对这本书感兴趣的话,可以看一下 试读样章),下面是文章的具体内容. ...

  5. python爬虫 - python requests网络请求简洁之道

    http://blog.csdn.net/pipisorry/article/details/48086195 requests简介 requests是一个很实用的Python HTTP客户端库,编写 ...

  6. 爬虫-Python爬虫常用库

    一.常用库 1.requests 做请求的时候用到. requests.get("url") 2.selenium 自动化会用到. 3.lxml 4.beautifulsoup 5 ...

  7. Python爬虫——Python 岗位分析报告

    前两篇我们分别爬取了糗事百科和妹子图网站,学习了 Requests, Beautiful Soup 的基本使用.不过前两篇都是从静态 HTML 页面中来筛选出我们需要的信息.这一篇我们来学习下如何来获 ...

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

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

  9. [爬虫]Python爬虫基础

    一.什么是爬虫,爬虫能做什么 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.比如它在抓取一个网 ...

随机推荐

  1. Java面试不得不知的问题(一)

    程序员面试   1. 面向对象的特征有哪些方面  ·   抽象:抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面.抽象并不打算了解全部问题,而只是选择其中的一部分, ...

  2. 【Java】多线程相关复习—— 线程的创建、名字、运行情况以及顺序控制(join方法) 【一】

    一.创建线程的三种方式 · 继承Thread类 · 实现Runnable接口 · 实现Callable接口 二. 线程状态 · 线程名字 getName() · 线程活动情况 isAlive() · ...

  3. 基于java开发的开源代码GPS北斗位置服务监控平台

    最近在研究位置服务平台,基于全球卫星定位技术(GNSS).互联网技术.空间地理信息技术(GIS).3G/4G无线通信技术,面向全国公众用户建立大容量.实时.稳定的位置信息服务运营平台.实现管理目标的实 ...

  4. 使用Git将本地项目上传到码云

    01.码云上创建一个项目 testgit (名字随意) 02.进入本地想要上传的目录,然后使用git bash 03.cd到想要上传的目录 04.$ git init 初始化一个git 本地仓库(项目 ...

  5. asciinema使用

    asciinema让您轻松记录终端会话,并在终端和网页浏览器中重播它们. 安装最新版本: sapt-get install asciinema 记录你的第一个终端视频: asciinema rec f ...

  6. scrapy--多爬虫

    大家好,我胡汉三又回来了!!!开心QAQ 由于最近一直在忙工作的事,之前学的一些爬虫知识忘得差不多了,只能再花多一些时间来回顾,否则根本无法前进.所以在这里也像高中老师那样提醒一下大家,--每天晚上花 ...

  7. ADSL_自动拨号源码(Delphi),已经测试通过

    下载地址: http://files.cnblogs.com/lwm8246/ADSL_%E8%87%AA%E5%8A%A8%E6%8B%A8%E5%8F%B7.rar

  8. 关于我的Android 博客

    我是曹新雨,我为自己代言.现在的菜鸟,3年以后我就是大神.为自己加油.微信:aycaoxinyu 关于我的Android博客,都是我当初遇到困难,克服之后,写上去的.后来,有人加我微信,问我一些问题, ...

  9. gettid 和pthread_self的区别

    转: Linux中,每个进程有一个pid,类型pid_t,由getpid()取得.Linux下的POSIX线程也有一个id,类型 pthread_t,由pthread_self()取得,该id由线程库 ...

  10. javascript类式继承模式#4——共享原型

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...