一、說明
本文主要講述采集貓眼電影用戶評論進行分析,相關(guān)爬蟲采集程序可以爬取多個電影評論。
運行環(huán)境:Win10/Python3.5。
分析工具:jieba、wordcloud、pyecharts、matplotlib。
基本流程:下載內(nèi)容 ---> 分析獲取關(guān)鍵數(shù)據(jù) ---> 保存本地文件 ---> 分析本地文件制作圖表
注意:本文所有圖文和源碼僅供學(xué)習(xí),請勿他用,轉(zhuǎn)發(fā)請注明出處!
本文主要參考:https://mp.weixin.qq.com/s/mTxxkwRZPgBiKC3Sv-jo3g
二、開始采集
2.1、分析數(shù)據(jù)接口:
為了健全數(shù)據(jù)樣本,數(shù)據(jù)直接從移動端接口進行采集,連接如下,其中橙色部分為貓眼電影ID,修改即可爬取其他電影。
鏈接地址:http://m.maoyan.com/mmdb/comments/movie/1208282.json?v=yes&offset=15&startTime=

接口返回的數(shù)據(jù)如下,主要采集(昵稱、城市、評論、評分和時間),用戶評論在 json['cmts'] 中:

2.2、爬蟲程序核心內(nèi)容(詳細可以看后面源代碼):
>啟動腳本需要的參數(shù)如下(腳本名+貓眼電影ID+上映日期+數(shù)據(jù)保存的文件名):./myMovieComment.py 1208282 2016-11-16 myCmts2.txt
>下載html內(nèi)容:download(self, url),通過python的requests模塊進行下載,將下載的數(shù)據(jù)轉(zhuǎn)成json格式
def download(self, url): """下載html內(nèi)容""" print("正在下載URL: "+url) # 下載html內(nèi)容 response = requests.get(url, headers=self.headers) # 轉(zhuǎn)成json格式數(shù)據(jù) if response.status_code == 200: return response.json() else: # print(html.status_code) print('下載數(shù)據(jù)為空!') return "">然后就是對已下載的內(nèi)容進行分析,就是取出我們需要的數(shù)據(jù):
def parse(self, content): """分析數(shù)據(jù)""" comments = [] try: for item in content['cmts']: comment = { 'nickName': item['nickName'], # 昵稱 'cityName': item['cityName'], # 城市 'content': item['content'], # 評論內(nèi)容 'score': item['score'], # 評分 'startTime': item['startTime'], # 時間 } comments.append(comment) except Exception as e: print(e) finally: return comments>將分析出來的數(shù)據(jù),進行本地保存,方便后續(xù)的分析工作:
def save(self, data): """寫入文件""" print("保存數(shù)據(jù),寫入文件中...") self.save_file.write(data)> 爬蟲的核心控制也即爬蟲的程序啟動入口,管理上面幾個方法的有序執(zhí)行:
def start(self): """啟動控制方法""" print("爬蟲開始.../r/n") start_time = self.start_time end_time = self.end_time num = 1 while start_time > end_time: print("執(zhí)行次數(shù):", num) # 1、下載html content = self.download(self.target_url + str(start_time)) # 2、分析獲取關(guān)鍵數(shù)據(jù) comments = '' if content != "": comments = self.parse(content) if len(comments) <= 0: print("本次數(shù)據(jù)量為: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("本次數(shù)據(jù)量:%s/r/n" % len(comments)) # 獲取最后一條數(shù)據(jù)的時間 ,然后減去一秒 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("爬蟲結(jié)束...")
新聞熱點
疑難解答