爬虫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爬虫基础
一.什么是爬虫,爬虫能做什么 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.比如它在抓取一个网 ...
随机推荐
- javaweb基础(40)_jdbc框架
一.元数据介绍 元数据指的是"数据库"."表"."列"的定义信息. 1.1.DataBaseMetaData元数据 Connection.g ...
- MyString类的实现--基础中的基础C语言
MyString 类是学习 C++ 的过程中一个很重要的例子,涉及到面向对象的封装.堆内存申请和释放.函数的重载以及 C++ 的 “Big Three”.本例子重点在于复习和理解上述的 C++ 特性, ...
- dts--framework(二)
Framwork下个文件中包含的函数 packet.py LayersTypes = { ', 'arp', 'lldp'], # ipv4_ext_unknown, ipv6_ext_unknown ...
- scrapy--dytt(电影天堂)
喜欢看电影的小伙伴,如果想看新的电影,然后没去看电影院看,没有正确的获得好的方法,大家就可以在电影天堂里进行下载.这里给大家提供一种思路. 1.dytt.py # -*- coding: utf-8 ...
- Android面试收集录 Android入门
1.Android的特点有哪些? 编程语言是Java或Kotlin,Android中的Java字节码是允许在Dalvik虚拟机上的 支持4大组件 Android内置了WebKit核心的浏览器,支持H5 ...
- 4,远程连接Linux
为什么要远程连接Linux 在实际的工作场景中,虚拟机界面或者物理服务器本地的终端都是很少接触的,因为服务器装完系统之后,都要拉倒IDC机房托管,如果是购买的云主机,那更碰不到服务器本体了,只能通过远 ...
- 15.3,redis持久化RDB与AOF
redis持久化 Redis是一种内存型数据库,一旦服务器进程退出,数据库的数据就会丢失,为了解决这个问题,Redis提供了两种持久化的方案,将内存中的数据保存到磁盘中,避免数据的丢失. RDB持久化 ...
- JsBridge "Uncaught TypeError: Cannot call method 'callHandler' of undefined", source
h5和原生结合开发app越来越流行.其实就是webview 的js调用native的方法.也就是需要搭建一个桥.这样的桥早就有人搭建好了,那就是jsbridge. git地址: https://git ...
- Result Maps collection does not contain value for XXXXX
在做mybatis多表查询的时候,出现了下面的错误: java.lang.IllegalArgumentException: Result Maps collection does not conta ...
- oracle(sql)基础篇系列(一)——基础select语句、常用sql函数、组函数、分组函数
花点时间整理下sql基础,温故而知新.文章的demo来自oracle自带的dept,emp,salgrade三张表.解锁scott用户,使用scott用户登录就可以看到自带的表. #使用oracle用 ...