Python 爬虫统计影评,超详细(按照步骤弄不出来杀楼主祭天)

来源:互联网 发布:电脑上的健身软件 编辑:程序博客网 时间:2024/05/16 23:35

在学习网络爬虫之前,先看一下完成效果吧,勾起大家的学习兴趣


图片中显示的文字,正是爬取的豆瓣电影中第一个正在热播的电影的评价中出现的高频词汇

是不是很有学习兴趣呀?准备开始Python的学习之旅吧,在学习之前先给大家透露一下

本次学习将会遇到许多许多坑


入门:配置爬虫开发环境

参照上一篇博客:http://blog.csdn.net/qq_36275193/article/details/78225236


1.对需要爬取数据的网页进行访问,爬取其HTML代码

resp = request.urlopen('https://movie.douban.com/nowplaying/hangzhou/')html_data = resp.read().decode('utf-8')

导入request包:

from urllib import request

此时可以  print(html_data) 来输出访问网页的信息

拿的网页的信息之后下一步就是对Html代码解析

2.解析获取到的HTML代码

解析获取到的HTML代码需要用到 BeautifulSoup 库

因为大家都刚安装Python 并没有添加过其它的库,所以要先安装  BeautifulSoup 库

安装步骤:

(1).打开CMD 

(2).输入 pip install BeautifulSoup

(3).耐心等待

安装完成的页面我已经不能提供喽,因为我已经安装过啦!

安装完成之后就可导入进行解析啦!


from bs4 import BeautifulSoup as bs (注: as bs 即给BeautifulSoup库起的一个小名, 类似SQL select u.cid from user u from user)

解析网页

soup = bs(html_data, 'html.parser')    (注: bs为BeautifulSoup库的小名)

print(soup) 可查看解析结果

3.获取所有电影列表

鼠标右键,查看源代码:


nowplaying_movie = soup.find_all('div', id='nowplaying')nowplaying_movie_list = nowplaying_movie[0].find_all('li', class_='list-item')

我们即可根据 层 的id 获取<li 标签 中的电影信息:

 即为获取所有的 <li >标签中的元素

4.解析电影的信息

因为打开进入电影评论页时需要电影的id



即可获取:

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)


可以print(nowplaying_list) 输出如下:



5.进入电影短评网址,获取短评



我们即可

然后解析获取的HTML代码:


结果如下:


但是,我们发现,拿到评论后,有这么些标点符号,这么些特殊字符,这怎么能作为我们的统计对象呢?所以我们要对数据进行清洗

6.数据清洗


print(cleaned_comments)打印一下清洗过的内容:


现在就是比较完美的字符串了,但是字符串怎么统计呢?

7.使用结巴分词库,进行分词

使用第三方库,结巴分词:

结巴官网下载:https://pypi.python.org/pypi/jieba/

下载之后解压,cmd进入文件夹 ,执行  python setup.py install

即可导入结巴库:


import jieba 

进行分词:

segment = jieba.lcut(cleaned_comments)


print(segment) 显示如下:


现在已经将评论分词,即可数据分析了。

8.数据分析:

数据分析需要使用库  pandas

安装步骤:

(1).打开CMD 

(2).输入 pip install pandas

(3).耐心等待

如果下载失败,可手动下载后,安装。

下载网址

http://pandas.pydata.org/

安装完成之后,导入包:

import pandas as pd

分析代码:

words_df = pd.DataFrame({'segment'})

print(words_df)

结果如下:


现在也分析词语后,就可统计词频了:

9.统计词频:


显示如下:

词频统计完成之后,就来到最后一步,词云显示

10.词云显示

词云显示会用到第三方库:WordCloud

安装步骤:

(1).打开CMD 

(2).输入 pip install wordCloud

(3).耐心等待

如果下载失败,可手动下载后,安装。

然后进行词云统计啦

先看看各个参数:


红色区域为 simkai font字体存放路径,如果你们没有,那是显示不了汉字的,所以看不到效果

 simaki.ttf下载地址: http://download.csdn.net/download/qq_36275193/10019644

红色区域为词云显示背景的形状图片,可选择任意图片

好了,当大家到这一步的时候,你就成功啦,可能因为我的代码正确,会引导你们少走弯路,如我遇到的坑:

当词云显示文本文档内的数据是,需要使用此方法:
path = open('d://test.txt').read()
WordCloud().generate(path)

但是,当显示已经处理过的数据时,因为已经做了统计,所以要使用另一种方法:

WordCloud().wordcloud.fit_words(wl_space_split)
wl_space_split 为已经处理过的数据

此方法是网上很多前辈给出的方法,我特么怎么都弄不出来,要气炸,一致于我认为我的数据出了问题,最后才知道,原来要这样:

wordcloud.fit_words(dict(word_frequence_list))

好啦! 爬虫入门就到此为止,昨天学习了python多线程,并发获取,这个就靠你们自己琢磨了呀!


附上完整代码:


#coding:utf-8__author__ = 'hang'import warningswarnings.filterwarnings("ignore")import jieba    #分词包import numpy    #numpy计算包import codecs   #codecs提供的open方法来指定打开的文件的语言编码,它会在读取的时候自动转换为内部unicodeimport reimport pandas as pdimport matplotlib.pyplot as pltfrom urllib import requestfrom bs4 import BeautifulSoup as bsimport matplotlibmatplotlib.rcParams['figure.figsize'] = (10.0, 5.0)from wordcloud import WordCloud#词云包from PIL import Image#分析网页函数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 eachCommentListdef main():    #循环获取第一个电影的前10页评论    commentList = []    NowPlayingMovie_list = getNowPlayingMovie_list()    for i in range(10):        num = i + 1        commentList_temp = getCommentsById(NowPlayingMovie_list[0]['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("‪C:/Users/admin/Desktop/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)    abel_mask = numpy.array(Image.open('c:/b319fd3a4c5994c8f4ce5679253a66e3.jpg'))    #用词云进行显示    wordcloud=WordCloud(font_path="‪D:/simkai.ttf",background_color="white",max_font_size=80,mask = abel_mask)    word_frequence = {x[0]:x[1] for x in words_stat.head(1000).values}    word_frequence_list = []    for key in word_frequence:        temp = (key,word_frequence[key])        word_frequence_list.append(temp)    wordcloud=wordcloud.fit_words(dict(word_frequence_list))    plt.imshow(wordcloud)    plt.show()#主函数main()





原创粉丝点击