爬虫python
最近看到电影,也看了很多的评论,想了解下大多人对相关电影的评论,正好也在学习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的更多相关文章
- 网易云音乐综合爬虫python库NetCloud v1版本发布
以前写的太烂了,这次基本把之前的代码全部重构了一遍.github地址是:NetCloud.下面是简单的介绍以及quick start. NetCloud--一个完善的网易云音乐综合爬虫Python库 ...
- 定向爬虫 - Python模拟新浪微博登录
当我们试图从新浪微博抓取数据时,我们会发现网页上提示未登录,无法查看其他用户的信息. 模拟登录是定向爬虫制作中一个必须克服的问题,只有这样才能爬取到更多的内容. 实现微博登录的方法有很多,一般我们在模 ...
- 百度图片爬虫-python版-如何爬取百度图片?
上一篇我写了如何爬取百度网盘的爬虫,在这里还是重温一下,把链接附上: http://www.cnblogs.com/huangxie/p/5473273.html 这一篇我想写写如何爬取百度图片的爬虫 ...
- 纯手工打造简单分布式爬虫(Python)
前言 这次分享的文章是我<Python爬虫开发与项目实战>基础篇 第七章的内容,关于如何手工打造简单分布式爬虫 (如果大家对这本书感兴趣的话,可以看一下 试读样章),下面是文章的具体内容. ...
- python爬虫 - python requests网络请求简洁之道
http://blog.csdn.net/pipisorry/article/details/48086195 requests简介 requests是一个很实用的Python HTTP客户端库,编写 ...
- 爬虫-Python爬虫常用库
一.常用库 1.requests 做请求的时候用到. requests.get("url") 2.selenium 自动化会用到. 3.lxml 4.beautifulsoup 5 ...
- Python爬虫——Python 岗位分析报告
前两篇我们分别爬取了糗事百科和妹子图网站,学习了 Requests, Beautiful Soup 的基本使用.不过前两篇都是从静态 HTML 页面中来筛选出我们需要的信息.这一篇我们来学习下如何来获 ...
- 零基础爬虫----python爬取豆瓣电影top250的信息(转)
今天利用xpath写了一个小爬虫,比较适合一些爬虫新手来学习.话不多说,开始今天的正题,我会利用一个案例来介绍下xpath如何对网页进行解析的,以及如何对信息进行提取的. python环境:pytho ...
- [爬虫]Python爬虫基础
一.什么是爬虫,爬虫能做什么 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.比如它在抓取一个网 ...
随机推荐
- Siamese Network
摘抄自caffe github的issue697 Siamese nets are supervised models for metric learning [1]. [1] S. Chopra, ...
- JDBC-Hibernate-Mybatis
JDBC sql语句和Java代码混在了一起 Hibernate 自动生成sql语句 Mybatis 将sql语句写在xml文件中,使用时动态生成
- Status bar - iOS之状态栏
(一)设置状态栏显示和隐藏 1.通过 Info.plist 文件增加字段,控制状态栏全局显示和隐藏 在 Info.plist 文件中增加字段 Status bar is initially hidde ...
- vue-router 实现分析
我们分别从不同的视角来看 vue-router. http://mp.weixin.qq.com/s?__biz=MzUxMzcxMzE5Ng==&mid=2247485737&idx ...
- P2661 信息传递 DFS
题目链接:洛谷 P2661 信息传递 一个人要想知道自己的生日,就意味着信息的传递是成环的,因为每轮信息只能传递一个人,传递的轮数就等于环的大小 环的大小就等于环中的两个点到第三个点的距离之和加一,我 ...
- 爬虫学习(十六)——jsonpath
jsonpath介绍 jsonpath是一种信息抽取类库,是从json文档中抽取指定信息的工具,提供多种语言实现的版本 jsonpath对json来说,就相当于xpath对于xml jsonpath和 ...
- Servlet学习笔记02——什么是http协议?
1.http协议 (了解) (1)什么是http协议? 是一种网络应用层协议,规定了浏览器与web服务器之间 如何通信以及相应的数据包的结构. 注: a.tcp/ip: 网络层协议,可以保证数据可靠的 ...
- oracle下表空间、用户创建以及用户授权流程
Oracle,表空间的建立.用户创建以及用户授权 主要是以下几步,挑选需要的指令即可: # 首先以scott用户作为sysdba登陆 conn scott/tiger as sysdba #创建用户 ...
- 局域网内使用ssh连接两台计算机总结
因为家里有两台电脑,一个centos7 系统,一个Mac,都是笔记本,感觉两个拿来拿去的用太麻烦了,所以就想用ssh连接cenots7 的电脑,这样就没那么麻烦了.欢迎大家指正 配置静态ip cent ...
- array_unique() - 去除数组中重复的元素值
array_unique() 定义和用法 array_unique() 函数移除数组中的重复的值,并返回结果数组. 当几个数组元素的值相等时,只保留第一个元素,其他的元素被删除. 返回的数组中键名 ...