爬虫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爬虫基础
一.什么是爬虫,爬虫能做什么 爬虫,即网络爬虫,大家可以理解为在网络上爬行的一直蜘蛛,互联网就比作一张大网,而爬虫便是在这张网上爬来爬去的蜘蛛咯,如果它遇到资源,那么它就会抓取下来.比如它在抓取一个网 ...
随机推荐
- vscode-tfs插件报错:TF30063
解决方案:删除tfs凭证,然后用vs重新登陆tfs服务器,此时会在电脑上创建要一个新的tfs凭证,然后再用vscode-tfs操作tfs就没有问题了.
- apache配置局域网访问
1.配置vhost.conf NameVirtualHost 192.168.2.74:80 <VirtualHost 192.168.2.74:80> DocumentRoot /var ...
- left join后面加上where条件浅析
select a.*,b.* from table1 a left join table2 b on b.X=a.X where XXX 如上:一旦使用了left join,没有where条件时,左表 ...
- Excel文档数据转成Plist文件
有时候我们需要导入大量数据到App中静态数据,但数据又是存在Excel中,怎么办? 第一,复制数据粘贴到一个.txt文本文档中 第二,就是撸代码了 比如,我需要导入的数据表有2列字段,name和bar ...
- python基础数据类型之字符串操作
1.字符串切片ps:字符串是不可变的对象, 所以任何操作对原字符 是不会有任何影响的 s1 = "python最简洁" print(s1[0]) print(s1[1]) prin ...
- ES6编程规范
andre es6 js
- DSP资源分享贴
DSP资源分享 [2017.5.16 更新] 分享资源共同学习.以前的资源很多人都说用不了了,我会陆续补充,逐步完善.这里不单单分享DSP的,设计基础的,还有其他的电子相关的比较好的资源吧主都和您分享 ...
- VIM配置IDE
转载于:https://blog.csdn.net/andre617/article/details/53496490#%E8%84%9A%E6%B3%A8 由于YCM需要vim支持python,需要 ...
- [CodeChef]RIN(最小割)
Description 有m门课可以在n个学期内学习,第i门课在第j个学期的收益是\(X_{i,j}\),一个学期可以学多门课,有的课之间有依赖关系,即必须先学a再学b,求最大收益.n,m<= ...
- dubbo的rpc异常
Exception in thread "main" com.alibaba.dubbo.rpc.RpcException: Failed to invoke the method ...