一、说明
本文主要讲述采集猫眼电影用户评论进行分析,相关爬虫采集程序可以爬取多个电影评论。
运行环境:Win10/Python3.5。
分析工具:jieba、wordcloud、pyecharts、matplotlib。
基本流程:下载内容 ---> 分析获取关键数据 ---> 保存本地文件 ---> 分析本地文件制作图表
注意:本文所有图文和源码仅供学习,请勿他用,转发请注明出处!
本文主要参考:https://mp.weixin.qq.com/s/mTxxkwRZPgBiKC3Sv-jo3g
二、开始采集
2.1、分析数据接口:
为了健全数据样本,数据直接从移动端接口进行采集,连接如下,其中橙色部分为猫眼电影ID,修改即可爬取其他电影。
链接地址:http://m.maoyan.com/mmdb/comments/movie/1208282.json?v=yes&offset=15&startTime=
接口返回的数据如下,主要采集(昵称、城市、评论、评分和时间),用户评论在 json['cmts'] 中:
2.2、爬虫程序核心内容(详细可以看后面源代码):
>启动脚本需要的参数如下(脚本名+猫眼电影ID+上映日期+数据保存的文件名):./myMovieComment.py 1208282 2016-11-16 myCmts2.txt
>下载html内容:download(self, url),通过python的requests模块进行下载,将下载的数据转成json格式
def download(self, url): """下载html内容""" print("正在下载URL: "+url) # 下载html内容 response = requests.get(url, headers=self.headers) # 转成json格式数据 if response.status_code == 200: return response.json() else: # print(html.status_code) print('下载数据为空!') return ""
>然后就是对已下载的内容进行分析,就是取出我们需要的数据:
def parse(self, content): """分析数据""" comments = [] try: for item in content['cmts']: comment = { 'nickName': item['nickName'], # 昵称 'cityName': item['cityName'], # 城市 'content': item['content'], # 评论内容 'score': item['score'], # 评分 'startTime': item['startTime'], # 时间 } comments.append(comment) except Exception as e: print(e) finally: return comments
>将分析出来的数据,进行本地保存,方便后续的分析工作:
def save(self, data): """写入文件""" print("保存数据,写入文件中...") self.save_file.write(data)
> 爬虫的核心控制也即爬虫的程序启动入口,管理上面几个方法的有序执行:
def start(self): """启动控制方法""" print("爬虫开始.../r/n") start_time = self.start_time end_time = self.end_time num = 1 while start_time > end_time: print("执行次数:", num) # 1、下载html content = self.download(self.target_url + str(start_time)) # 2、分析获取关键数据 comments = '' if content != "": comments = self.parse(content) if len(comments) <= 0: print("本次数据量为:0,退出爬取!/r/n") break # 3、写入文件 res = '' for cmt in comments: res += "%s###%s###%s###%s###%s/n" % (cmt['nickName'], cmt['cityName'], cmt['content'], cmt['score'], cmt['startTime']) self.save(res) print("本次数据量:%s/r/n" % len(comments)) # 获取最后一条数据的时间 ,然后减去一秒 start_time = datetime.strptime(comments[len(comments) - 1]['startTime'], "%Y-%m-%d %H:%M:%S") + timedelta(seconds=-1) # start_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S") # 休眠3s num += 1 time.sleep(3) self.save_file.close() print("爬虫结束...")
新闻热点
疑难解答