爬虫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爬虫基础
一.什么是爬虫,爬虫能做什么 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.比如它在抓取一个网 ...
随机推荐
- 使用C#的新特性:可空类型
随着C#语言最新标准的出炉,现在它也提供了对可空类型的支持.这个小变化将会在处理那些包括可选项的数据库记录时非常有用.当然在其他地方,它也是非常有用的. 简单说来,可空数据类型就是包含了所定义的数据类 ...
- Make a Person-freecodecamp算法题目
Make a Person 1.要求 用下面给定的方法构造一个对象:方法有 getFirstName(), getLastName(), getFullName(), setFirstName(fir ...
- 【杂题总汇】Codeforces-67A Partial Teacher
[Codeforces-67A]Partial Teacher 上周刷了一大堆小紫薯的动态规划的题
- js对象动态添加属性,方法
1. 动态添加属性,方法 var object = new Object(); object.name = "name"; object.age = 19; >>> ...
- Centos7 使用LVM进行新加磁盘管理
centos7使用LVM管理一块新的磁盘 注意!文中凡是带#的都是命令标志. 一些重要概念: LV(Logical Volume)- 逻辑卷, VG(Volumne Group)- 卷组, P ...
- 银行卡验证API
一.银联开放平台 https://open.unionpay.com/tjweb/api/detail?apiSvcId=21 应用场景 综合数据服务平台是银联为接入商户提供的综合数据认证服务接口,目 ...
- js如何获得系统时间年月日时分秒
javascript 自带有个对象(构造函数),Date().下面是代码: 回答一: var now = new Date(); var nowTime = now.toLocaleString() ...
- php扩展开发-资源类型
资源类型在内核中的结构 //zend_list.h typedef struct _zend_rsrc_list_entry { void *ptr; int type; int refcount; ...
- My jdbc 错误
jdbc mysql插入数据提示Parameter index out of range (1 > number of parameters, which is 0). SqlStatement ...
- java多线程批量读取文件(七)
新公司入职一个多月了,至今没有事情可以做,十来个新同事都一样抓狂,所以大家都自己学习一些新东西,我最近在看zookeeper,感觉蛮不错的,和微服务的zuul以及eureka功能类似,只是代码复杂了一 ...